POJ 3984 迷宫问题 bfs+回溯

poj 3984 迷宫问题

Description

定义一个二维数组:

int maze[5][5] = {

0, 1, 0, 0, 0,

0, 1, 0, 1, 0,

0, 0, 0, 0, 0,

0, 1, 1, 1, 0,

0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

题目链接
推荐类似的BFS+回溯的一道题:poj3414

思路:
简单的bfs+回溯
注意一个坑:输出时,(4, 4)逗号后面有一个空格

代码:

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

using namespace std;

int step[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
int maze[6][6];
int cost[6][6];
int visit[6][6];
const int INF = 1e5;
int ans = INF;
int r=5, c=5;
struct node {
	int x, y;
	node* pre;	//指向上一状态的指针,便于回溯得出解的过程
	node(int x, int y) { this->x = x, this->y = y; }
};

void print_ans(node* ans)	//通过栈和pre指针进行回溯得到解的过程
{
	stack<node*> s;
	while (ans != NULL)
	{
		s.push(ans);
		ans = ans->pre;
	}
	while (!s.empty())
	{
		node * t = s.top();
		s.pop();
		printf("(%d, %d)\n", t->x, t->y);	//注意逗号后面有一个空格
	}
}
void bfs()
{
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
			cost[i][j] = INF, visit[i][j] = 0;//初始化
	queue<node*> q;
	node* a = new node(0, 0);
	visit[0][0] = 1;
	cost[0][0] = 1;
	a->pre = NULL;
	q.push(a);
	while (!q.empty())
	{
		node* t = q.front();
		q.pop();
		if (t->x == r - 1 && t->y == c - 1) {	//得出答案
			print_ans(t);
			return;
		}
		for (int i = 0; i < 4; i++)
		{
			int x = t->x, y = t->y;
			x += step[i][0], y += step[i][1];
			if (x >= 0 && x < r &&y >= 0 && y < c && !visit[x][y] && !maze[x][y]) {
				visit[x][y] = 1;
				cost[x][y] = cost[t->x][t->y] + 1;
				node* next = new node(x, y);
				next->pre = t;
				q.push(next);
			}
		}
	}
}

int main()
{
		for (int i = 0; i < r; i++)
		{
			for (int j = 0; j < c; j++)
			{
				cin >> maze[i][j];
			}
		}
		bfs();
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值