迷宫:
S****
*###*
*###*
*###*
****T
升级版:找到迷宫中的路径数目 path number 并输出路径以及路径数
#include<iostream>
using namespace std;
#include<algorithm>
//输入一个地图,然后找出口
char maze[20][20];
bool vis[20][20];
int n, m, ans=0;
int dir[2][4] = { {1,0,-1,0},
{0,-1,0,1 } };
void dfs(int x, int y,int step) {
if (maze[x][y] == 'T') {
ans++;
cout << "path number:" << ans << endl;
cout << step << endl;
cout << x << "," << y << endl;
return;
}
vis[x][y] = true;
/*
int tx = x + 1;
int ty = y;
if (tx >= 0 && tx < m && ty >= 0 && ty < n && maze[tx][ty] != '#' && vis[tx][ty] == false) {
if(dfs(tx, ty,step+1))
return true;
}
tx = x;
ty = y - 1;
if (tx >= 0 && tx < m && ty >= 0 && ty < n && maze[tx][ty] != '#' && vis[tx][ty] == false) {
if(dfs(tx, ty,step+1))
return true;
}
tx = x - 1;
ty = y;
if (tx >= 0 && tx < m && ty >= 0 && ty < n && maze[tx][ty] != '#' && vis[tx][ty] == false) {
if(dfs(tx, ty,step+1))
return true;
}
tx = x;
ty = y + 1;
if (tx >= 0 && tx < m && ty >= 0 && ty < n && maze[tx][ty] != '#' && vis[tx][ty] == false) {
if(dfs(tx, ty,step+1))
return true;
}
//上下左右都不能走的话回退
*/
int tx = 0;
int ty = 0;
//由于有for循环在,第一次被访问的路径中的i再次访问时不可能再次访问同一个方向了,i++了,只能访问其他方向了。
for (int j = 0; j < 4; j++) {
tx = x + dir[0][j];
ty = y + dir[1][j];
if (tx >= 0 && tx < n && ty >= 0 && ty < m && maze[tx][ty] != '#' && vis[tx][ty] == false) {
vis[tx][ty] == true;
dfs(tx, ty, step + 1);
cout <<x << "," << y << endl;
vis[tx][ty] == false;
}
}
vis[x][y] == false;
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> maze[i][j];
vis[i][j] = false;
}
}
int x, y;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (maze[i][j] =='S') {
x = i;
y = j;
dfs(x, y, 0);
cout << "找到出口啦" << endl;
}
}
}
}