https://www.acwing.com/problem/content/1078/
思路:当边权都相等时,可以用bfs寻找最短路。记录路径也很重要,因为第一次搜索到的一定是最短的,所以我们可以开一个二维数组记录每个点的前一个状态是什么,然后从终点搜索起点,这样从起点开始输出就是路径啦。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 1010;
typedef struct
{
int x, y;
}P;
int a[maxn][maxn], n;
P p[maxn][maxn];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
void bfs()
{
queue<P> q;
q.push({n - 1, n - 1});
while(q.size())
{
P t = q.front();
q.pop();
for(int i = 0;i < 4; i++)
{
int xx = t.x + dx[i];
int yy = t.y + dy[i];
if(xx >= 0 && xx < n && yy >= 0 && yy < n && a[xx][yy] == 0)
{
q.push({xx, yy});
p[xx][yy] = t;
a[xx][yy] = 1;
}
}
}
}
int main()
{
scanf("%d", &n);
for(int i = 0;i < n; i++)
for(int j = 0;j < n; j++)
scanf("%d", &a[i][j]);
bfs();
P ans = {0, 0};
while(true)
{
printf("%d %d\n", ans.x, ans.y);
if(ans.x == n - 1 && ans.y == n - 1) break;
ans = p[ans.x][ans.y];
}
return 0;
}在这里插入代码片