poj 3984 迷宫问题

本文介绍了一个基于广度优先搜索(BFS)算法来寻找迷宫从起点到终点的最短路径并打印路径的方法。通过递归回溯的方式记录路径,最终实现了路径的完整输出。

做这道题其实我是想看看打印路径的方法,挺水的,看了网上别人的代码,打印路径基本上都是保存一下父节点,然后

打印出它的坐标,我写的是递归一下,从后面向前找到起点,找的过程有点不一样,之前没保存,而是继续上下左右的

找,估计是因为这个时间有点多,虽然在这道题上看不出来差别。。。无意中看到了盈神的博客,我做这道题将近比她晚了一年。。。

代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue> 
int dist[10][10];
int visit[10][10];
int gra[10][10];
const int dx[4] = {-1,1,0,0};
const int dy[4] = {0,0,-1,1};
using namespace std;
struct node
{
	int x,y;
};
void bfs(int x,int y)
{
	int i;
	queue<node>que;
	memset(visit,0,sizeof(visit));
	memset(dist,0,sizeof(dist));
	node n1;
	n1.x = x;
	n1.y = y;
	dist[x][y] = 0;
	que.push(n1);
	visit[x][y] = 1;
	while(!que.empty())
	{
		node n1 = que.front();
		que.pop();
		if((n1.x == 5) && (n1.y == 5))
		{
			//printf("%d\n",dist[n1.x][n1.y]);
			return ;
		}
		for(i=0; i<4; i++)
		{
			int xx = n1.x + dx[i];
			int yy = n1.y + dy[i];
			if(!visit[xx][yy] && (gra[xx][yy] == 0) && (xx >= 1) && (xx <= 5) &&(yy >= 1) && (yy <= 5))
			{
				visit[xx][yy] = 1;
				dist[xx][yy] = dist[n1.x][n1.y] + 1;
				node n2;
				n2.x = xx,n2.y = yy;
				que.push(n2);
			}
		}
	}
}
void print_path(node n1,node n2)
{
	int i;
	if((n2.x == n1.x) && (n1.y == n2.y))
		return;
	for(i=0; i<4; i++)
	{
		int xx = n2.x + dx[i];
		int yy = n2.y + dy[i];
		if((dist[n2.x][n2.y] == dist[xx][yy] + 1) && visit[xx][yy])
		{
			node n3;
			n3.x =xx,n3.y =yy;
			print_path(n1,n3);
			printf("(%d, %d)\n",n3.x-1,n3.y-1);
		}
	}
	return ;
}
int main()
{
	int i,j;
	for(i=1; i<=5; i++)
		for(j=1; j<=5; j++)
			scanf("%d",&gra[i][j]);
	bfs(1,1);	
	node n1,n2;
	n1.x = 1, n1.y = 1;
	n2.x = 5, n2.y = 5;
	print_path(n1,n2);
	printf("(4, 4)");
	return 0;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值