# bfs 记录和打印最短路径

## Poj3984 迷宫问题

``` 1 #include <iostream>
2 #include <algorithm>
3 #include <cstdio>
4 #include <queue>
5 using namespace std;
6 int maze[5][5];
7 int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
8
9 //用结构体来记录更方便
10 struct Node
11 {
12     int x ,y ;
13     int prex ,prey;  //前一节点坐标
14     int dis ; //记录是第几层访问的节点
15 } s[5][5];
16
17
18 void bfs(int x, int y)
19 {
20 //队列来实现bfs
21     queue <Node> q;
22     q.push(s[0][0]);  //加入头节点
23     s[0][0].dis = 0;
24     s[0][0].x=0;
25     s[0][0].y=0;
26     while(!q.empty())
27     {
28         Node temp = q.front();
29         int tx = temp.x;
30         int ty = temp.y;
31         int tdis = temp.dis;
32
33         if(tx == 4 && ty == 4)    //终止条件
34             return;
35
36         for(int i = 0; i < 4; i++)
37         {
38             int row = tx + dir[i][0];
39             int col = ty + dir[i][1];
40             if(row >=0 && row < 5 && col >=0 && col < 5 && maze[row][col] != 1)
41             {
42                 maze[row][col] = 1;
43                 s[row][col].x = row;
44                 s[row][col].y = col;
45                 s[row][col].prex = tx;
46                 s[row][col].prey = ty;
47                 s[row][col].dis = tdis + 1;  //有了这一步，便可知道最短路径的长度！
48                 q.push(s[row][col]);
49             }
50         }
51         q.pop();
52
53
54
55     }
56
57 }
58
59 //递归打印路径！从后往前，打印从前往后
60 void print_path(int x,int y)
61 {
62
63     if(x == 0 && y == 0)  //终止条件，打印第一个
64     {
65         cout<<"("<<s[0][0].x<<", "<<s[0][0].y<<")"<<endl;
66         return;
67     }
68
69     int prex = s[x][y].prex;
70     int prey = s[x][y].prey;
71     print_path(prex,prey);
72     cout<<"("<<s[x][y].x<<", "<<s[x][y].y<<")"<<endl;
73 }
74
75 int main()
76 {
77     for(int i = 0; i < 5; i++)
78         for(int j = 0; j < 5; j++)
79             cin>>maze[i][j];
80     bfs(0,0);
81     //cout<<s[4][4].dis<<endl;
82     print_path(4,4);
83     return 0;
84 }```

View Code

 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 10536 Accepted: 6263

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

Input

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)```