#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
int map[5][5];
bool vis[5][5];
int dir[4][4] = {{0,1},{0,-1},{1,0},{-1,0}};
struct Node{
int x,y;
};
Node pre[5][5];
// 找到目标节点后,从pre数组中找到第一个节点,从第一个节点开始遍历
void out(Node now){
if(now.x == 0 && now.y == 0){
printf("(%d, %d)\n",now.x,now.y);
return;
}
out(pre[now.x][now.y]);
printf("(%d, %d)\n",now.x,now.y);
}
void bfs(){
queue<Node> q;
Node start;
start.x = 0,start.y = 0;
q.push(start); //存入起点,开始广搜
vis[0][0] = 1;
while(!q.empty()){
Node now = q.front();
q.pop();
if(now.x == 4 && now.y == 4){
out(now);
return;
}
for(int i = 0;i<4;i++){
Node next;
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
//符合条件就存入队列,等待下一轮广搜
if(!vis[next.x][next.y] && !map[next.x][next.y] && next.x >=0 && next.x <5 && next.y < 5 && next.y >= 0){
vis[next.x][next.y] = 1;
q.push(next);
//要注意保存当前节点的前一个节点
pre[next.x][next.y] = now;
}
}
}
}
int main(){
for(int i = 0;i<5;i++)
for(int j = 0;j<5;j++)
cin >> map[i][j];
bfs();
return 0;
}
与dfs不同,bfs是按照层次进行的,一层扫完才开始扫下一层,一但在某一层中找到targe,就结束bfs。
注意:
要把每一层中的节点存入队列,然后每次循环都弹出队列头,找他的后继节点