BFS入门---poj3984

#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。

注意:

        要把每一层中的节点存入队列,然后每次循环都弹出队列头,找他的后继节点

         

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值