洛谷 1746. P1746 离开中山路
原题链接
中等
作者:
Agoni7z
,
2024-01-23 18:51:25
,
所有人可见
,
阅读 40
// Problem: P1746 离开中山路
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1746
// Memory Limit: 125 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
char g[N][N];
int dist[N][N];
queue<PII> q;
int x1, x2, y1, y2;
int n;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int bfs(int x1, int y1) {
memset(dist, -1, sizeof dist);
q.push({x1, y1});
dist[x1][y1] = 0;
while (!q.empty()) {
auto t = q.front();
q.pop();
for(int i = 0; i < 4; i ++ ) {
int a = t.first + dx[i], b = t.second + dy[i];
if (a < 1 || a > n || b < 1 || b > n) continue;
if (g[a][b] != '0') continue;
if (dist[a][b] > 0) continue;
q.push({a, b});
dist[a][b] = dist[t.first][t.second] + 1;
}
}
return dist[x2][y2];
}
int main() {
cin >> n;
for (int i = 1; i <= n; i ++ ) cin >> g[i] + 1;
cin >> x1 >> y1 >> x2 >> y2;
int ans = bfs(x1, y1);
cout << ans << '\n';
return 0;
}