水题,直接跑一边网格图BFS即可。
#include<bits/stdc++.h>
using i64 = long long;
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
int main() {
std::cin.tie(nullptr)->sync_with_stdio(false);
int n, m;
std::cin >> n >> m;
int sx, sy, ex, ey;
std::cin >> sx >> sy >> ex >> ey;
sx--; sy--; ex--; ey--;
std::vector<std::string> a(n);
for (auto &s : a) std::cin >> s;
int inf = 1e9;
std::vector dis(n, std::vector<int>(m, inf));
dis[sx][sy] = 0;
std::queue<std::pair<int, int>> q;
q.push({sx, sy});
while (q.size()) {
auto [x, y] = q.front(); q.pop();
for (int w = 0; w < 4; w++) {
int nx = x + dx[w];
int ny = y + dy[w];
if (nx >= 0 && ny >= 0 && nx < n && ny < m && a[nx][ny] =='.' && dis[nx][ny] > dis[x][y] + 1) {
dis[nx][ny] = dis[x][y] + 1;
q.push({nx, ny});
}
}
}
std::cout << (dis[ex][ey] == inf ? -1 : dis[ex][ey]);
return 0;
}

京公网安备 11010502036488号