POJ 3984---迷宫问题(BFS,迷宫最短路径且输出路径)

原题:

BFS入门题,打印路径记录前驱就可以了。然后可以递归打印,也可以非递归打印路径:

递归打印路径:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<stack>

using namespace std;

int maze[6][6];
int vis[6][6], dist[6][6];
int dr[] = { -1,1,0,0 };
int dc[] = { 0,0,1,-1 };

struct node
{
	int r, c;
}pre[6][6];
queue<node>Q;
void bfs()
{
	while (!Q.empty())Q.pop();
	memset(vis, 0, sizeof(vis));
	dist[0][0] = 0;
	node tmp;
	tmp.c = tmp.r = 0;
	Q.push(tmp);
	while (Q.size())
	{
		node tmp = Q.front(); Q.pop();
		int r = tmp.r, c = tmp.c;
		for (int i = 0; i < 4; i++)
		{
			int nr = r + dr[i], nc = c + dc[i];
			if (nr >= 0 && nr <= 4 && nc >= 0 && nc <= 4 && !vis[nr][nc] && maze[nr][nc] == 0)
			{
				vis[nr][nc] = 1;
				tmp.c = nc;
				tmp.r = nr;
				Q.push(tmp);
				dist[nr][nc] = dist[r][c] + 1;
				tmp.r = r; tmp.c = c; 
				pre[nr][nc] = tmp; //丫丫的,好不方便~可是我不会C++呀。
				if (nr == 4 && nc == 4)return;
			}
		}
	}
}
void print(int x, int y) //递归打印
{
	if (x == 0 && y == 0)return;
	print(pre[x][y].r, pre[x][y].c);
	printf("(%d, %d)\n", pre[x][y].r, pre[x][y].c);
}
int main()
{
	for(int i=0;i<5;i++)
		for (int j = 0; j < 5; j++)
			cin >> maze[i][j];
	bfs();	
	print(4, 4);
	cout << "(4, 4)" << endl;
	system("pause");
}

非递归:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<stack>

using namespace std;

int maze[6][6];
int vis[6][6], dist[6][6];
int dr[] = { -1,1,0,0 };
int dc[] = { 0,0,1,-1 };

struct node
{
	int r, c;
}pre[6][6];
queue<node>Q;
void bfs()
{
	while (!Q.empty())Q.pop();
	memset(vis, 0, sizeof(vis));
	dist[0][0] = 0;
	node tmp;
	tmp.c = tmp.r = 0;
	Q.push(tmp);
	while (Q.size())
	{
		node tmp = Q.front(); Q.pop();
		int r = tmp.r, c = tmp.c;
		for (int i = 0; i < 4; i++)
		{
			int nr = r + dr[i], nc = c + dc[i];
			if (nr >= 0 && nr <= 4 && nc >= 0 && nc <= 4 && !vis[nr][nc] && maze[nr][nc] == 0)
			{
				vis[nr][nc] = 1;
				tmp.c = nc;
				tmp.r = nr;
				Q.push(tmp);
				dist[nr][nc] = dist[r][c] + 1;
				tmp.r = r; tmp.c = c; 
				pre[nr][nc] = tmp; //丫丫的,好不方便~可是我不会C++呀。
				if (nr == 4 && nc == 4)return;
			}
		}
	}
}
int main()
{
	for(int i=0;i<5;i++)
		for (int j = 0; j < 5; j++)
			cin >> maze[i][j];
	bfs();	
	stack<node>S;
	int cur_r = 4, cur_c = 4;
	while (1)
	{
		node tmp;
		tmp.r = cur_r;
		tmp.c = cur_c;
		S.push(tmp);
		if (cur_r == 0 && cur_c == 0)
			break;
		int r = cur_r, c = cur_c;
		cur_r = pre[r][c].r;
		cur_c = pre[r][c].c;
	}
	while (S.size())
	{
		node tmp = S.top(); S.pop();
		printf("(%d, %d)\n", tmp.r, tmp.c);

	}
	system("pause");
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值