题目背景
《爱与愁的故事第三弹·shopping》最终章。
题目描述
爱与愁大神买完东西后,打算坐车离开中山路。现在爱与愁大神在 x1,y1 处,车站在 x2,y2 处。现在给出一个 n×n(n≤1000) 的地图,0 表示马路,1 表示店铺(不能从店铺穿过),爱与愁大神只能垂直或水平着在马路上行进。爱与愁大神为了节省时间,他要求最短到达目的地距离(每两个相邻坐标间距离为 1)。你能帮他解决吗?
输入格式
第 1 行包含一个数 n。
第 2 行到第 n+1 行:整个地图描述(0 表示马路,1 表示店铺,注意两个数之间没有空格)。
第 n+2 行:四个数 x1,y1,x2,y2。
输出格式
只有 1 行,即最短到达目的地距离。
输入输出样例
输入 #1
3 001 101 100 1 1 3 3
输出 #1
4
说明/提示
对于 20% 数据,满足 1≤n≤100。
对于 100% 数据,满足 1≤n≤1000。
代码
#include<bits/stdc++.h>
using namespace std;
int n, bx, by, ex, ey;
char g[1005][1005];
int dx[] = { -1,0,1,0 };
int dy[] = { 0,1,0,-1 };
struct node {
int x, y, step;
};
void bfs() {
queue<node>q;
q.push(node{ bx,by,0 });
g[bx][by] = '1';
while (!q.empty()) {
node now = q.front();
q.pop();
if (now.x == ex && now.y == ey) {
cout << now.step;
return;
}
for (int i = 0; i < 4; i++) {
node next = node{ now.x + dx[i],now.y + dy[i],now.step + 1 };
if (next.x >= 1 && next.x <= n && next.y >= 1 && next.y <= n && g[next.x][next.y] == '0') {
q.push(next);
g[next.x][next.y] = '1';
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) cin >> g[i][j];
}
cin >> bx >> by >> ex >> ey;
bfs();
return 0;
}