要求
给定一个大小为n * m(n <= 100, m <= 100)的迷宫。迷宫由通道(0)和墙壁(#)组成,每一步可以向邻接的上下左右四格的通道移动。请求出从起点到终点所需的最小步数。请注意,本题假定从起点一定可以移动到终点。
输入格式
输入n、m、起点(x, y)、终点(x, y)
输出格式
输出从起点到终点的最短距离
测试输入
5 5 0 0 3 3
0 # 0 0 0
0 0 # 0 #
0 0 # 0 #
0 # 0 0 0
0 0 0 # 0
测试输出
8
解题思路
- 深度优先搜索:
从起点开始,使用深度优先搜索(DFS,Depth-First Search),从now沿着一条方向一直走,直到无法行走,再退回now,选择另一个方向继续行走,直到所有dist里存的都是最短距离。
dist[][]为从起点到某点的距离。 - 宽度优先搜索:
从起点开始,一点点向外扩展,相当于每个点只走一次,并记录到达当前点所用的消耗,因为是从起点向外扩展,所以消耗总是最小的。
代码
#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);
cout << dist[end.first][end.second] << endl;
return 0;
}
#include<iostream>
#include<queue>
using namespace std;
#define MAX 0x7f7f
int main() {
char map[101][101];
pair<int, int> start;
pair<int, int> end;
int n, m;
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];
}
}
int dist[101][101];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dist[i][j] = MAX;
}
}
queue<pair<int, int> > que;
dist[start.first][start.second] = 0;
que.push(start);
int fx[4] = {1,0,-1,0};
int fy[4] = {0,1,0,-1};
while (que.size()) {
pair<int, int> now;
now = que.front();
que.pop();
if (now == end) {
break;
}
for (int i = 0; i < 4; i++) {
int nx = now.first + fx[i];
int ny = now.second + fy[i];
if (nx >= 0 && ny >= 0 && nx < n && ny < m && map[nx][ny] != '#' && dist[nx][ny] == MAX) {
que.push(pair<int, int>(nx, ny));
dist[nx][ny] = dist[now.first][now.second] + 1;
}
}
}
cout << dist[end.first][end.second] << endl;
return 0;
}