算法1
DFS+BFS
一遍BFS求最短路,然后用一个数组保存路径,用一遍DFS打印路径
C++ 代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 1005;
struct{
int a, b;
}path[maxn][maxn];
bool vis[maxn][maxn] = {false};
int G[maxn][maxn], n, dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
void BFS(int x, int y)
{
queue<pair<int, int> > q;
q.push({x, y});
while(!q.empty())
{
pair<int, int> temp = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
int nx = temp.first + dx[i];
int ny = temp.second + dy[i];
if(nx >= 0 && nx < n && ny >= 0 && ny < n && G[nx][ny] == 0)
{
if(vis[nx][ny] == false)
{
q.push({nx, ny});
vis[nx][ny] = true;
path[nx][ny].a = temp.first;
path[nx][ny].b = temp.second;
}
}
}
}
}
void DFS(int x, int y)
{
if(x == 0 && y == 0)
{
printf("%d %d\n", x, y);
return;
}
DFS(path[x][y].a, path[x][y].b);
printf("%d %d\n", x, y);
}
int main()
{
cin >> n;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
cin >> G[i][j];
BFS(0, 0);
DFS(n - 1, n - 1);
return 0;
}