Topic links: Click here
to become the way through the wall, that is,
is set to
, so as to achieve the purpose of weight determination
Output path: an array simulation queue structure, pre recorded before a queue element index in the array, when it reaches the end, recursive backtracking back output path.
Note: BFS itself already contains the shortest property, so once they reach the end, it is the shortest route, the output can be.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1010, M = N * N;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
struct node {
int x, y, pre; // pre记录前一个元素在队列数组中的下标
node() {}
node(int _x, int _y, int _p) : x(_x), y(_y), pre(_p) {}
};
int n;
int g[N][N];
int hh = 0, tt = -1; // 队首和队尾
node q[M]; // 数组模拟队列
void print(node t)
{
if(t.pre == -1)
{
printf("%d %d\n", t.x, t.y);
return;
}
print(q[t.pre]);
printf("%d %d\n", t.x, t.y);
}
void bfs()
{
q[++tt] = node(0, 0, -1);
g[0][0] = 1;
while(hh <= tt)
{
node t = q[hh]; // 取队首元素
for(int i = 0; i < 4; ++i)
{
int nx = t.x + dx[i], ny = t.y + dy[i];
if(nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
if(g[nx][ny] == 1) continue;
q[++tt] = node(nx, ny, hh);
g[nx][ny] = 1;
if(nx == n - 1 && ny == n - 1) return; // 到达终点
}
hh++; // 删队首元素
}
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
scanf("%d", &g[i][j]);
bfs();
print(q[tt]);
return 0;
}