就一个最短路,并且边长都是1,所以每个点只搜一次。
1 /************************************************************** 2 Problem: 3299 3 User: MT_Chan 4 Language: C++ 5 Result: Accepted 6 Time:72 ms 7 Memory:2420 kb 8 ****************************************************************/ 9 10 #include<cstdio> 11 #include<cstdlib> 12 #include<cstring> 13 #include<iostream> 14 #include<algorithm> 15 #include<queue> 16 using namespace std; 17 #define Maxn 310 18 #define INF 0xfffffff 19 20 int kx[30]; 21 int a[Maxn][Maxn],tr[Maxn*Maxn]; 22 char s[Maxn]; 23 24 int dis[Maxn*Maxn],st,ed; 25 int n,m; 26 27 queue<int > q; 28 void spfa() 29 { 30 while(!q.empty()) q.pop(); 31 memset(dis,-1,sizeof(dis)); 32 q.push(st);dis[st]=0; 33 while(!q.empty()) 34 { 35 int x=q.front(); 36 int nx=(x-1)/m+1,ny=x-(nx-1)*m; 37 if(ny>1&&tr[x-1]!=-1&&dis[tr[x-1]]==-1) 38 { 39 dis[tr[x-1]]=dis[x]+1; 40 if(tr[x-1]==ed) break; 41 q.push(tr[x-1]); 42 } 43 if(ny<m&&tr[x+1]!=-1&&dis[tr[x+1]]==-1) 44 { 45 dis[tr[x+1]]=dis[x]+1; 46 if(tr[x+1]==ed) break; 47 q.push(tr[x+1]); 48 } 49 if(nx>1&&tr[x-m]!=-1&&dis[tr[x-m]]==-1) 50 { 51 dis[tr[x-m]]=dis[x]+1; 52 if(tr[x-m]==ed) break; 53 q.push(tr[x-m]); 54 } 55 if(nx<n&&tr[x+m]!=-1&&dis[tr[x+m]]==-1) 56 { 57 dis[tr[x+m]]=dis[x]+1; 58 if(tr[x+m]==ed) break; 59 q.push(tr[x+m]); 60 } 61 q.pop(); 62 } 63 printf("%d\n",dis[ed]); 64 } 65 66 int main() 67 { 68 scanf("%d%d",&n,&m); 69 memset(kx,-1,sizeof(kx)); 70 memset(tr,0,sizeof(tr)); 71 for(int i=1;i<=n;i++) 72 { 73 scanf("%s",s); 74 for(int j=0;j<m;j++) 75 { 76 int now=(i-1)*m+j+1; 77 if(s[j]==‘@‘) st=now; 78 else if(s[j]==‘=‘) ed=now; 79 else if(s[j]==‘#‘) tr[now]=-1; 80 else if(s[j]>=‘A‘&&s[j]<=‘Z‘) 81 { 82 int kk=s[j]-‘A‘+1; 83 if(kx[kk]==-1) kx[kk]=now; 84 else tr[now]=kx[kk],tr[kx[kk]]=now; 85 } 86 } 87 } 88 for(int i=1;i<=n*m;i++) if(tr[i]==0) tr[i]=i; 89 spfa(); 90 return 0; 91 }
时间: 2024-10-25 20:43:48