这个题是一个很简单的bfs,但是与之前的不同是它需要记录路径,哈哈哈哈哈哈哈哈想了一下午终于会记录了好开心~
Problem Description
给你一个5*5的二维数组,表示一个迷宫,0可以走,1不可以走,问你从左上角到右下角,最短的路径,保证数据有唯一的解。
Code:
#include <bits/stdc++.h>
using namespace std;
struct node
{
int x;
int y;
};
int a[12][12], book[12][12], dict[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
node pre[12][12];
bool judge(int x, int y)
{
if(x < 0 || x > 4 || y < 0 || y > 4 || book[x][y])
return false;
return true;
}
void print(node a)
{
if(a.x || a.y)
{
print(pre[a.x][a.y]);
//递归倒叙输出
printf("(%d, %d)\n", a.x, a.y);
}
return;
}
void bfs(int u, int v)
{
queue<node> q;
q.push((node){u, v});
book[u][v] = 1;
while(!q.empty())
{
node v = q.front();
q.pop();
if(v.x == 4 && v.y == 4)
{
print(pre[v.x][v.y]);
return ;
}
for(int i = 0; i < 4; i++)
{
node t;
t.x = v.x + dict[i][0];
t.y = v.y + dict[i][1];
if(judge(t.x, t.y) && !a[t.x][t.y])
{
q.push(t);
book[t.x][t.y] = 1;
pre[t.x][t.y] = (node){v.x, v.y};
//关键,记录上一个点的信息
}
}
}
}
int main()
{
int i, j;
for(i = 0; i < 5; i++)
for(j = 0; j < 5; j++)
scanf("%d", &a[i][j]);
printf("%d, %d)\n", 0, 0);
bfs(0, 0);
printf("(%d, %d)\n", 4, 4);
}
“因为bfs中每个点都只走一次,所以每个走过的节点只有一个前驱结点,如果一个前驱结点被走过,那么一定可以顺着这个找到前驱结点找到起点” – 摘自某大神