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

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;
}

你可能感兴趣的:(bfs,&,dfs,OJ题解,bfs,回溯)