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

發佈了69 篇原創文章 · 獲贊 34 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章