本题要求:
给定一个大小为n * m(n <= 100, m <= 100)的迷宫。迷宫由通道(0)和墙壁(#)组成,每一步可以向邻接的上下左右四格的通道移动。请求出从起点出发是否可以到达终点。
输入格式:
输入n、m、起点(x, y)、终点(x, y)
接下来n*m输入地图
输出格式:
可以到达输出”Yes”,否则输出“No”
输入样例:
5 5 0 0 3 3
0 # 0 0 0
0 0 # 0 #
0 0 # 0 #
0 # 0 0 0
0 # 0 # 0
输出样例:
Yes
解题思路 :
代码 :
#include<iostream>
using namespace std;
#define MAX 0x7f7f
char map[101][101];
int dist[101][101];
int n, m;
pair<int, int> start, end;
void dfs(pair<int, int> now, int last) {
if (now.first < 0 || now.first >= n || now.second < 0 || now.second >=m || map[now.first][now.second] == '#') {
return;
}
if (dist[now.first][now.second] > last + 1) {
dist[now.first][now.second] = last + 1;
} else {
return;
}
dfs(pair<int, int>(now.first, now.second + 1), dist[now.first][now.second]);
dfs(pair<int, int>(now.first + 1, now.second), dist[now.first][now.second]);
dfs(pair<int, int>(now.first, now.second - 1), dist[now.first][now.second]);
dfs(pair<int, int>(now.first -1, now.second), dist[now.first][now.second]);
}
int main() {
cin >> m >> n;
cin >> start.first >> start.second >> end.first >> end.second;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[j][i];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dist[i][j] = MAX;
}
}
dfs(start,-1);
if (dist[end.first][end.second] ==MAX) {
cout << "Yes";
} else {
cout << "No";
}
return 0;
}