#include<iostream>
using namespace std;
#include<algorithm>
//输入一个地图,然后找出口
//S**##
//*#*##
//##*##
//##**#
//##**T
char maze[20][20];
bool vis[20][20];
int n, m;
int dir[2][4] = { {1,0,-1,0},
{0,-1,0,1 } };
bool dfs(int x, int y,int step) {
if (maze[x][y] == 'T') {
cout << step << endl;
cout << x << "," << y << endl;
return true;
}
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 (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) {
if (dfs(tx, ty, step + 1))
cout << x << "," << y << endl;
return true;
}
}
vis[x][y] == false;
return 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;
if (dfs(x, y,0) ){
cout << "找到出口啦" << endl;
}
else
cout << "lose" << endl;
}
}
}
}
从S开始,到T为迷宫的出口 ,在一个n*m大小的迷宫内搜索出口
代码思路:一开始从字符为S的位置开始遍历,从每个坐标的右,下,左,上的顺序依次遍历
一开始是dfs(0,0,0),之后在dfs(0,0,0)中调用dfs(0,1,1),再在dfs(0,1,1)中调用dfs(0,2,2),
一直递归调用到dfs(4,4,8)出口的位置,输出dfs(4,4,8)的函数返回值,由于dfs,(4,3,7)调用的dfs(4,4,8)所以紧接着才输出的方式(4,3,7)的返回值,依次如下
8
4,4
4,3
4,2
3,2
2,2
1,2
0,2
0,1
0,0