1.简单介绍下dfs(深度优先搜索):它的思想是从一个顶点V0开始,沿着一条路一直走到底,如果发现不能到达目标解,那就返回到上一个节点,然后从另一条路开始走到底,这种尽量往深处走的概念即是深度优先的概念。
2.以样例
3 3
S..
..E
...
为解释
先给个图解释下这个过程(隔离ing,画的不好,辛苦同学们看了)。
什么情况不可以走
1.墙
2.迷宫外的点
3.已经走过的点
对最后一个稍微做一下解释:若走到1,3点,总会有个循环使得往1,3点的左侧走,此时如果没有标记1,2点那它就是符合条件的点,进入1,2点就总会有一个循环往右走进入1,3点...所以需要标记走过的点。
注:走出迷宫的路径不一定是图中所画,这取决于我们先走哪个方向的(上,下,左,右 || 左,右,上,下) 且按照上,下,左,右的方向走出去的路径应是1,1->2,1->2,2->2,3。
ac代码
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 510;
int dy[4] = {0,0,-1,1};
int dx[4] = {-1,1,0,0};//dx dy 是走的方向
char map[N][N];
bool isout = false;
int m, n;
int sx, sy, ex, ey;//s对应start,e对应end
void dfs(int x, int y);
bool isgo(int x, int y);
int main() {
while (cin >> n >> m) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
if (map[i][j] == 'S') sx = i, sy = j;
else if (map[i][j] == 'E') ex = i, ey = j;
}
}
isout = false;
dfs(sx, sy);
if (isout) cout << "Yes" << endl;
else cout << "No" << endl;
}
}
void dfs(int x, int y) {
if (x == ex && ey == y) {
isout = true;
return;
}
map[x][y] = '1';//标记走过的路
//枚举方向
for (int i = 0; i < 4; i++) {
int cur_x = x + dx[i], cur_y = y + dy[i];
if (isgo(cur_x, cur_y)) dfs(cur_x, cur_y);
}
}
//不能走的点
bool isgo(int x, int y) {
if (x > n - 1 || y > m - 1 || x < 0 || y < 0) return false;
if (map[x][y] == '1') return false;
if (map[x][y] == '#') return false;
return true;
}