poj3984迷宫问题(dfs+stack)

时间:2023-03-09 09:31:47
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)
 #include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<vector>
#include<stack>
using namespace std;
int a[][];
const int n=;
stack <pair<int,int> >stk;
bool dfs(int i,int j) {
if(i==n-&&j==n-) {
stk.push(make_pair(i,j));
return true;
}
if (i >= && i <= n - && j >= && j <= n - ) { // 判断边界
if (a[i][j] == ) { // 可以走且没走过
a[i][j] = ;// 表示走过
if (dfs(i, j + ) || dfs(i + , j) || dfs(i, j - ) || dfs(i - , j)) { // 接着走
stk.push(make_pair(i,j));
return true;
} else { // 回溯
a[i][j] = ;
return false;
}
} else {
return false;
}
} else {
return false;
}
}
int main() {
for(int i=; i<; i++) {
for(int j=; j<; j++) {
scanf("%d",&a[i][j]);
}
}
dfs(,);
while(!stk.empty()) {
printf("(%d, %d)\n",stk.top().first,stk.top().second);
stk.pop();
}
return ;
}