AcWing 1076. 迷宫问题
考察:bfs
错误思路:
定义结构体Node,用Node里vector记录路径.
此思路会TLE,当n很大时,每次赋值都要消耗一定时间.
正确思路:
用数组记录路径,即用PII 数组记录到达该点的上一步的坐标.到时候再迭代即可.
注意:当迭代的时候,不要重新定义PII it!!!!!
最最注意:如果取单个坐标迭代,x y 是时刻在改变的!!!!!
1 #include <iostream> 2 #include <cstring> 3 #include <queue> 4 using namespace std; 5 const int N = 1010; 6 typedef pair<int,int> PII; 7 int n,xx[4] = {-1,1,0,0},yy[4]={0,0,-1,1}; 8 bool mp[N][N]; 9 PII pre[N][N]; 10 void bfs(int x,int y) 11 { 12 queue<PII> q; 13 q.push({x,y}); 14 pre[x][y] = {0,0}; 15 while(q.size()) 16 { 17 PII it = q.front(); 18 q.pop(); 19 int nx= it.first,ny =it.second; 20 if(nx==1&&ny==1) return; 21 for(int i=0;i<4;i++) 22 { 23 int dx = nx+xx[i],dy=ny+yy[i]; 24 if(dx>=1&&dx<=n&&dy>=1&&dy<=n&&!mp[dx][dy]&&pre[dx][dy].first==-1) 25 { 26 pre[dx][dy] = {nx,ny}; 27 q.push({dx,dy}); 28 } 29 } 30 } 31 } 32 int main() 33 { 34 scanf("%d",&n); 35 for(int i=1;i<=n;i++) 36 for(int j=1;j<=n;j++) 37 scanf("%d",&mp[i][j]); 38 memset(pre,-1,sizeof pre); 39 bfs(n,n); 40 PII it(1,1); 41 while(1) 42 { 43 printf("%d %d\n",it.first-1,it.second-1); 44 if(it.first==n&&it.second==n) break; 45 it = pre[it.first][it.second]; 46 } 47 return 0; 48 }