Poj 3984 迷宫问题(BFS+DFS打印路径)

题意:输出从左上到右下的路径。

题解:BFS。也不解释了。唯一一点就是这个和我之前用队列模拟的查找路径不太一样。详细看代码拒接。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;

int map[10][10];   // 地图 
int book[10][10];  // 标记数组 

int mov[4][2]={1,0,-1,0,0,1,0,-1};  // 移动数组 
struct node {
	int x;
	int y;
};
node lu[10][10];  // 记录路径 记录该点是从那点得来的 
queue<node> q;
void print(node s){   // DFS打印路径 
	if(s.x == 0 && s.y == 0){
		printf("(%d, %d)\n",s.x,s.y);
		return ;
	}
	print(lu[s.x][s.y]);
	printf("(%d, %d)\n",s.x,s.y);
}
void bfs(){
	book[0][0] = 1;
	while(!q.empty()) q.pop();
	node now ,next;
	now.x = 0;
	now.y = 0;
	q.push(now);
	while(!q.empty()){
		now = q.front();
		q.pop();
		if(now.x == 4 && now.y == 4){  // 判断达到终点 
			//printf("GOOD GAME\n");
			print(now);
		}
		for(int i = 0 ; i < 4 ; i ++){
			next.x = now.x + mov[i][0];
			next.y = now.y + mov[i][1];
			if(next.x < 0 || next.y < 0 || next.x > 4 || next.y > 4 || book[next.x][next.y] || map[next.x][next.y])  // 判断是否可行 
				continue;
			book[next.x][next.y] = 1;
			lu[next.x][next.y] = now; 
			q.push(next);
		}	
	}
}
int main(){
	for(int i = 0 ; i < 5 ; i++){
		for(int j = 0 ; j < 5 ; j++)
			scanf("%d",&map[i][j]);
	}
	bfs();
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值