poj-3984 迷宮問題

定義一個二維數組:

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)

據說測試數據很水的一道題,用dfs寫錯了交上去居然還過了。
用bfs找最短路,用遞歸輸出路徑。

代碼:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
int mp[5][5];//存圖
bool vis[5][5];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
typedef struct node
{
	int x,y;
}no;
node r[5][5];//定義一個二維的結構體
int check(int x,int y)//檢查
{
	if(x>=0&&x<5&&y>=0&&y<5&&vis[x][y]==false&&mp[x][y]==0)
		return 1;
	else
		return 0;
}
void pri(int x1,int y1)//遞歸打印
{
	if(x1==0&&y1==0)
	{
		printf("(0, 0)\n");
		return;
	}
	pri(r[x1][y1].x,r[x1][y1].y);
	printf("(%d, %d)\n",x1,y1);
}
int main()
{
	int x1,y1;
	memset(mp,0,sizeof(mp));
	memset(vis,false,sizeof(vis));
	for(int i=0;i<5;i++)
		for(int j=0;j<5;j++)
			cin>>mp[i][j];
	node now;//當前位置
	node next;//下一位置
	queue<node> q;
	now.x=0,now.y=0;
	q.push(now);
	vis[0][0]=true;
	while(!q.empty())//bfs
	{
		now=q.front();
		q.pop();
		if(now.x==4&&now.y==4)//最快找到終點的那條一定是最短路
			break;
		for(int i=0;i<4;i++)
		{
			x1=now.x+dir[i][0];
			y1=now.y+dir[i][1];
			if(check(x1,y1))
			{
				next.x=x1,next.y=y1;
				vis[x1][y1]=true;
				q.push(next);
				r[x1][y1].x=now.x;//重點!通過二維結構體記錄父子節點關係
				r[x1][y1].y=now.y;
			}
		}	
	}
	pri(4,4);
	//system("pause");
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章