POJ3984BFS记录路径

定义一个二维数组: 

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<stdio.h>  
 2 #include<string.h>  
 3 #include<stdlib.h>  
 4 #include<iostream>
 5 using namespace std;
 6 struct point
 7 {
 8     int x;
 9     int y;
10 }list[100];
11 int map[5][5];
12 int vis[5][5];
13 int pre[101];
14 int u[4][2]={1,0,-1,0,0,1,0,-1};
15 void print(int t)
16 {
17     int x=pre[t];
18     if(x==0)
19     {
20         printf("(0, 0)
");
21         printf("(%d, %d)
",list[t].x,list[t].y);
22     }
23     else
24     {
25         print(x);
26         printf("(%d, %d)
",list[t].x,list[t].y);
27     }
28 }
29 void bfs(int x1,int y1)
30 {
31     int head,next,i;
32     memset(vis,0,sizeof(vis));
33     list[0].x=x1;
34     list[0].y=y1;
35     pre[0]=-1;
36     head=0;
37     next=1;
38     while(head<next)
39     {
40         int x=list[head].x;
41         int y=list[head].y;
42         if(x==4&&y==4)
43         {
44             print(head);
45             return ;
46         }
47         for(int i=0;i<4;i++)
48         {
49             int tx=list[head].x+u[i][0];
50             int ty=list[head].y+u[i][1];
51             if(tx>=0&&tx<5&&ty>=0&&ty<5&&map[tx][ty]==0&&vis[tx][ty]==0)
52             {
53                 vis[tx][ty]=1;
54                 list[next].x=tx;
55                 list[next].y=ty;
56                 pre[next]=head;
57                 next++;
58             }
59         }
60         head++;
61     }
62 }
63 int main()  
64 {  
65     for(int i=0;i<5;i++)
66     for(int j=0;j<5;j++)
67     cin>>map[i][j];
68     bfs(0,0);
69     return 0;
70 }  
原文地址:https://www.cnblogs.com/--lr/p/7219834.html