link0636 @ 2024-03-17 17:10:18
#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int N = 1010;
typedef pair<int, int> PII;
queue <PII> q;
int p[N][N];
int x1, y1, x2,y2;
int dist[N][N];
int dx[] = { -1,0,1,0 };
int dy[] = { 0,-1,0,1 };
int n;
int BFS(int x1, int y1)
{
memset(dist, -1, sizeof(dist));
q.push({x1,y1});
dist[x1][y1] = 0;
while (q.size())
{
PII t = q.front();
q.pop();
for (int i = 1; i <= 4; i++)
{
int a = dx[i] + t.first; int b = t.second + dy[i];
if (a<1 || a>n || b<1 || b>n) { continue; }
if (p[a][b] == 1) { continue; }
if (dist[a][b] != -1) { continue; }
q.push({ a,b });
dist[a][b] = dist[t.first][t.second] + 1;
if (a == x2 && b == y2) { return dist[x2][y2]; }
}
}return dist[x2][y2];
}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
scanf("%1d", &p[i][j]);
}
}
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
printf("%d", BFS(x1, y1));
return 0;
}
by 656gmg @ 2024-03-18 21:23:02
向量数组的遍历应该是for (int i = 0; i < 4; i++)