天天看點

poj3984迷宮問題(dfs+stack)

迷宮問題

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 35426 Accepted: 20088

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)
題意:給出一個迷宮矩陣,輸出一條通路
題解:dfs找到一條通路,并用棧記錄(poj用萬能頭檔案會CE emmmm)      
1 #include<cstdio>
 2 #include<cstring>
 3 #include<string>
 4 #include<cmath>
 5 #include<iostream>
 6 #include<algorithm>
 7 #include<map>
 8 #include<set>
 9 #include<queue>
10 #include<vector>
11 #include<stack>
12 using namespace std;
13 int a[20][20];
14 const int n=5;
15 stack <pair<int,int> >stk;
16 bool dfs(int i,int j) {
17     if(i==n-1&&j==n-1) {
18         stk.push(make_pair(i,j));
19         return true;
20     }
21     if (i >= 0 && i <= n - 1 && j >= 0 && j <= n - 1) { // 判斷邊界
22         if (a[i][j] == 0) { // 可以走且沒走過
23             a[i][j] = 1;// 表示走過
24             if (dfs(i, j + 1) || dfs(i + 1, j) || dfs(i, j - 1) || dfs(i - 1, j)) { // 接着走
25                 stk.push(make_pair(i,j));
26                 return true;
27             } else { // 回溯
28                 a[i][j] = 0;
29                 return false;
30             }
31         } else {
32             return false;
33         }
34     } else {
35         return false;
36     }
37 }
38 int main() {
39     for(int i=0; i<5; i++) {
40         for(int j=0; j<5; j++) {
41             scanf("%d",&a[i][j]);
42         }
43     }
44     dfs(0,0);
45     while(!stk.empty()) {
46         printf("(%d, %d)\n",stk.top().first,stk.top().second);
47         stk.pop();
48     }
49     return 0;
50 }      

轉載于:https://www.cnblogs.com/fqfzs/p/9883770.html