小明置身于一个迷宫,请你帮小明找出从起点到终点的最短路程。
小明只能向上下左右四个方向移动。
输入格式:
第一行是两个整数n和m (1≤ m, n ≤100),表示迷宫的长和宽。接下来是n行,每行m个数字,表示整个迷宫。空地格子用0表示,障碍物用1表示,小明所在起点用3表示,终点用4表示。
输出格式:
如果能够到达终点,输出一个整数,表示小明从起点到目的地所需的最短时间。如果不能到达终点,输出“unreachable”。
输入样例1:
5 5
1 0 1 1 1
1 0 4 1 0
1 0 0 1 0
0 0 0 1 0
1 0 3 0 1
输出样例1:
3
输入样例2:
5 5
3 0 1 1 1
1 0 1 1 0
1 0 1 1 0
0 0 0 1 0
1 0 1 0 4
输出样例2:
unreachable
#include<iostream>
#include<vector>
#include<queue>
#include<utility>
using namespace std;
typedef pair<char, char> ptr;
struct Node {
ptr start;
int step;
};
vector<vector<char>> maze(100, vector<char>(100, '1'));
vector<vector<bool>> visited(100, vector<bool>(100, false));
vector<ptr> dir = { {1,0},{0,1},{-1,0},{0,-1} };
void bfs(ptr start, ptr end) {
queue<Node> p;
p.push({ start,0 });
bool found = false;
while (!p.empty()) {
Node q = p.front();
p.pop();
if (q.start == end) {
found = true;
cout << q.step << endl;
break;
}
for (int i = 0;i < 4;i++) {
int tx = q.start.first + dir[i].first;
int ty = q.start.second + dir[i].second;
if (tx >= 0 && tx < 100 && ty >= 0 && ty < 100 && maze[tx][ty] == '0' && !visited[tx][ty]) {
visited[tx][ty] = true;
p.push({ {tx,ty},q.step + 1 });
}
}
}
if (!found)
cout << "unreachable" << endl;
}
int main() {
int n, m;
cin >> n >> m;
ptr start, end;
for (int i = 0;i < n;i++) {
for (int j = 0;j < m;j++) {
cin >> maze[i][j];
if (maze[i][j] == '3') {
start = { i,j };
maze[i][j] = '0';
}
if (maze[i][j] == '4') {
end = { i,j };
maze[i][j] = '0';
}
}
}
bfs(start, end);
return 0;
}