POJ 3984 -- 迷宫问题

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6059   Accepted: 3502

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)
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<limits.h>
 4 int maze[10][10],mark[10][10];
 5 const int di[4]={1,0,-1,0};
 6 const int dj[4]={0,1,0,-1};
 7 int Step;
 8 typedef struct{
 9     int x,y;
10 }R;
11 struct{
12     R data[1000];
13 }rec,Rec;
14 void dfs(int step,int x,int y){
15     int px;
16     int py;
17     for(int k=0;k<4;k++){
18         px=x+di[k];
19         py=y+dj[k];
20         if(maze[px][py]==0&&mark[px][py]==0){
21             step++;
22             rec.data[step].x=px;
23             rec.data[step].y=py;
24             mark[px][py]=1;
25             if(px==5&&py==5){
26                 if(step<Step){Step=step;Rec=rec;}
27             }
28             else dfs(step,px,py);
29             //回溯 
30             step--;
31             mark[px][py]=0;
32         }
33     }
34 }
35 int main(){
36     for(int i=1;i<=5;i++)for(int j=1;j<=5;j++)scanf("%d",&maze[i][j]);
37     for(int i=0;i<=6;i++)maze[0][i]=maze[6][i]=maze[i][0]=maze[i][6]=1;
38     Step=INT_MAX;
39     mark[1][1]=1;
40     rec.data[1].x=1;
41     rec.data[1].y=1;
42     dfs(1,1,1);
43     for(int i=1;i<=Step;i++)printf("(%d, %d)
",Rec.data[i].x-1,Rec.data[i].y-1);
44     return 0;
45 }
原文地址:https://www.cnblogs.com/gangduo-shangjinlieren/p/3187341.html