题目
题解思路
之前的喜欢在入队的时候加入路径,这样导致内存和时间都挺浪费的。
其实可以开一个数组 ,反着跑bfs,用数组记录前一个的节点。
在输出的时候就直接正着输出就行了。(有点链表的感觉)
用之前的办法T了。
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1010 ;
int n ;
int mp [N][N] ;
int vis [N][N] ;
int dx[4] = {-1,1,0,0} ;
int dy[4] = {0,0,1,-1} ;
struct node
{
int x,y;
};
node lu [N][N] ;
void bfs()
{
queue <node> q ;
q.push({n-1,n-1}) ;
vis[n-1][n-1] = 1 ;
while(!q.empty())
{
node tmp = q.front() ;
q.pop() ;
if ( tmp.x == 0 && tmp.y == 0 )
{
cout << 0 <<" " << 0 << "\n" ;
node tp = lu[tmp.x][tmp.y];
while( 1 )
{
cout << tp.x <<" " << tp.y << "\n" ;
if ( tp.x == n-1 && tp.y == n-1 )
break;
tp = lu[tp.x][tp.y] ;
}
return ;
}
// cout << tmp.x << " " << tmp.y << "\n";
for (int i = 0 ; i < 4 ; i++ )
{
int fx = tmp.x + dx[i] ;
int fy = tmp.y + dy[i] ;
if ( fx >= 0 && fy >= 0 && fx < n && fy < n && mp[fx][fy] == 0 && vis[fx][fy] == 0 )
{
vis[fx][fy] = 1 ;
lu[fx][fy] = {tmp.x,tmp.y} ;
q.push({fx,fy});
}
}
}
}
int main ()
{
ios::sync_with_stdio(false);
cin >> n ;
for (int i = 0 ; i < n ; i++ )
for (int j = 0 ; j < n ; j++ )
cin >> mp[i][j] ;
bfs();
return 0 ;
}