一本通-1215:迷宫(经典迷宫类型DFS)¶
【题目描述】 一天Extense在森林里探险的时候不小心走入了一个迷宫,迷宫可以看成是由n * n的格点组成,每个格点只有2种状态,.和#,前者表示可以通行后者表示不能通行。同时当Extense处在某个格点时,他只能移动到东南西北(或者说上下左右)四个方向之一的相邻格点上,Extense想要从点A走到点B,问在不走出迷宫的情况下能不能办到。如果起点或者终点有一个不能通行(为#),则看成无法办到。
【输入】 第1行是测试数据的组数k,后面跟着k组输入。每组测试数据的第1行是一个正整数n (1 ≤ n ≤ 100),表示迷宫的规模是n * n的。接下来是一个n * n的矩阵,矩阵中的元素为.或者#。再接下来一行是4个整数ha, la, hb, lb,描述A处在第ha行, 第la列,B处在第hb行, 第lb列。注意到ha, la, hb, lb全部是从0开始计数的。
【输出】 k行,每行输出对应一个输入。能办到则输出“YES”,否则输出“NO”。
【输入样例】
2
3
.##
..#
#..
0 0 2 2
5
.....
###.#
..#..
###..
...#.
0 0 4 0
【输出样例】 YES NO
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <string>
#include <climits>
#include <cstdio>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <set>
#include <algorithm>
using namespace std;
int m,n;
vector<vector<char> > grid(105, vector<char>(105));
vector<vector<bool> > used(105, vector<bool>(105, false));
int direction[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};
int desRow, desCol;
bool DFS(int row, int col)
{
used[row][col] = true;
if (row == desRow && col == desCol) return true;
bool flag = false;
for (int i = 0; i < 4; ++i) {
int nextRow = row + direction[i][0];
int nextCol = col + direction[i][1];
if (0 <= nextRow && nextRow < m && 0 <= nextCol && nextCol < n
&& !used[nextRow][nextCol] && grid[nextRow][nextCol] == '.') {
flag |= DFS(nextRow, nextCol);
if (flag) break;
//used[nextRow][nextCol] = false;
}
}
return flag;
}
int main()
{
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int caseNum; cin >> caseNum;
while (caseNum--) {
cin >> m; n = m;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
cin >> grid[i][j];
}
}
int row, col; cin >> row >> col >> desRow >> desCol;
if (DFS(row, col)) cout << "YES" << endl;
else cout << "NO" << endl;
for (int i = 0; i < m; ++i) fill(used[i].begin(), used[i].begin() + n, false);
}
return 0;
}
这里需要注意以下,迷宫搜索不需要回退,因为如果从一个点无法达到终点,那么后续无论从哪个点搜索过来到当前点都无法到达终点,所以不需要回退。