#include<bits/stdc++.h>
using namespace std;
int n, x, y, ex, ey;
char s[1002][1002];
struct node {
int x, y, step;
}q[1000001]; // x坐标, y坐标,到这个点时走了几步
int nex[4][2] = {0, -1, 1, 0, 0, 1, -1, 0};
bool book[1002][1002];
int main() {
cin >> n;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++)
cin >> s[i][j];
}
cin >> x >> y >> ex >> ey;
int head = 1, tail = 1; // 指向队列头, 指向队列尾
q[head].x = x;
q[head].y = y;
q[head].step = 0;
// 起点先入队,步数为0
tail++;
// 尾 + 1,方便下一个点入队
while(head < tail) {
for(int i = 0; i < 4; i++) {
int tx = q[head].x + nex[i][0];
int ty = q[head].y + nex[i][1];
if(tx < 1 || tx > n || ty < 1 || ty > n) continue;
// 越界
if(s[tx][ty] == '1' || book[tx][ty] == 1) continue;
// 障碍物, 已经走过
// 符合条件的点,入队 ↓↓↓↓↓
q[tail].x = tx;
q[tail].y = ty;
q[tail].step = q[head].step + 1;
tail++;
book[tx][ty] = 1; // 标记已经走过了
if(tx == ex && ty == ey) {
cout << q[tail - 1].step; // 因为每个点入队后,tail都要 + 1变成新的,
// 所以这里需要-1
return 0;
}
}
head++; // 头指针+1
}
return 0;
}
洛谷P1746 离开中山路(BFS、手打队列、板子题)
最新推荐文章于 2024-04-26 22:05:26 发布