1. 程式人生 > >poj 3984 迷宮問題

poj 3984 迷宮問題

body align 最短路 lan end strong std iss spa

                        迷宮問題
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 27854 Accepted: 16056

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)

Source

#include<cstdio>
#include<cstring>
#include<iostream>
#include
<algorithm> using namespace std; int map[6][6]; int ans=0x7f7f7f7f; int dx[4]={1,-1,0,0}; int dy[4]={0,0,1,-1}; int ansx[40],ansy[40]; int tmpx[40],tmpy[40]; void dfs(int x,int y,int step){ if(step>ans) return ; if(x==4&&y==4){ if(step>ans) return ; ans
=step; for(int i=1;i<=step;i++){ ansx[i]=tmpx[i]; ansy[i]=tmpy[i]; } return ; } for(int i=0;i<4;i++){ int cx=x+dx[i]; int cy=y+dy[i]; if(cx>=0&&cx<=4&&cy>=0&&cy<=4&&!map[cx][cy]){ tmpx[step+1]=cx; tmpy[step+1]=cy; map[cx][cy]=1; dfs(cx,cy,step+1); map[cx][cy]=0; } } } int main(){ for(int i=0;i<5;i++) for(int j=0;j<5;j++) scanf("%d",&map[i][j]); dfs(0,0,0); printf("(0, 0)\n"); for(int i=1;i<=ans;i++) cout<<"("<<ansx[i]<<", "<<ansy[i]<<")"<<endl; }

poj 3984 迷宮問題