BFS
图的遍历过程,其实可以抽象为一颗树的层次遍历过程,通过一个根结点,向外一层一层的遍历,直至抵达目的终点或者遍历完整颗子树。
下面通过POJ3984题对BFS算法流程进行简单描述
POJ3984
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int mp[10][10];
int vis[10][10];
const int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
struct node{
int x,y;
};
node pr[10][10];
void BFS(){
memset(vis,0,sizeof(vis));
node n,next;
queue<node> q;
n.x=0;
n.y=0;
q.push(n);
while(!q.empty()){
n=q.front();
q.pop();
if(n.x==4&&n.y==4){
return;
}
for(int i=0;i<4;i++){
int x=n.x+dir[i][0];
int y=n.y+dir[i][1];
if(x>=0&&x<5&&y>=0&&y<5&&mp[x][y]!=1&&vis[x][y]!=1){
vis[x][y] = 1;
next.x=x;
next.y=y;
q.push(next);
pr[next.x][next.y]=n;//通过当前节点寻找上一个节点,逆序输出
}
}
}
}
void print(node a){
if(a.x==0&&a.y==0){
printf("%d %d\n",a.x,a.y);
return;
}
print(pr[a.x][a.y]);//通过后一节点循迹上一节点,
//pr[4][4]=[3,4]
//pr[3][4]=[2,4]
//....
printf("%d %d\n",a.x,a.y);
}
int main(){
node n;
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
scanf("%d",&mp[i][j]);
BFS();
n.x=4;
n.y=4;
print(n);
return 0;
}
整体算法流程与树的层次遍历几乎相同