题目
分析
- bfs跑两遍
代码
1 #include<iostream> 2 #include<cstring> 3 #include<queue> 4 using namespace std; 5 int map[100][100]; 6 int wa[100][100],dis[100][100],flag[100][100]; 7 int fx[5][2]={{0,0},{0,1},{1,0},{-1,0},{0,-1}}; 8 int n,m,x1,y1,x2,y2; 9 queue<int> q; 10 void bfs() 11 { 12 while (!q.empty()) 13 { 14 int x=q.front(); q.pop(); int y=q.front(); q.pop(); 15 for (int i=1;i<=4;i++) 16 { 17 int ax=x+fx[i][0],ay=y+fx[i][1]; 18 if (ax<1||ax>n||ay<1||ay>m||map[ax][ay]||flag[ax][ay]) continue; 19 wa[ax][ay]=min(wa[x][y]+1,wa[ax][ay]); 20 q.push(ax); q.push(ay); 21 flag[ax][ay]=1; 22 } 23 } 24 } 25 void bbfs() 26 { 27 memset(dis,0x3f,sizeof(dis)); 28 memset(flag,0,sizeof(flag)); 29 while (!q.empty()) q.pop(); 30 q.push(x1); q.push(y1); dis[x1][y1]=1; 31 while (!q.empty()) 32 { 33 int x=q.front(); q.pop(); int y=q.front(); q.pop(); 34 for (int i=1;i<=4;i++) 35 { 36 int ax=x+fx[i][0],ay=y+fx[i][1]; 37 if (ax<1||ax>n||ay<1||ay>m||map[ax][ay]||flag[ax][ay]||wa[ax][ay]<=dis[x][y]+1) continue; 38 dis[ax][ay]=min(dis[x][y]+1,dis[ax][ay]); 39 q.push(ax); q.push(ay); 40 flag[ax][ay]=1; 41 } 42 } 43 } 44 int main () 45 { 46 char c; 47 cin>>n>>m; 48 memset(wa,0x7f,sizeof(wa)); 49 for (int i=1;i<=n;i++) 50 { 51 for (int j=1;j<=m;j++) 52 { 53 cin>>c; 54 if (c=='D') x2=i,y2=j; 55 else if (c=='S') x1=i,y1=j; 56 else if (c=='X') map[i][j]=1; 57 else if (c=='*') q.push(i),q.push(j),wa[i][j]=1,flag[i][j]=1; 58 } 59 } 60 map[x2][y2]=1; 61 bfs(); 62 map[x2][y2]=0; 63 bbfs(); 64 if (dis[x2][y2]!=1061109567) cout<<dis[x2][y2]-1; 65 else cout<<"KAKTUS"; 66 }