最短路-离开中山路
作者:互联网
离开中山路
题目背景
《爱与愁的故事第三弹·shopping》最终章。
题目描述
爱与愁大神买完东西后,打算坐车离开中山路。现在爱与愁大神在x1,y1处,车站在x2,y2处。现在给出一个n×n(n<=1000)的地图,0表示马路,1表示店铺(不能从店铺穿过),爱与愁大神只能垂直或水平着在马路上行进。爱与愁大神为了节省时间,他要求最短到达目的地距离(a[i][j]距离为1)。你能帮他解决吗?
输入格式
第1行:一个数 n
第2行~第n+1行:整个地图描述(0表示马路,1表示店铺,注意两个数之间没有空格)
第n+2行:四个数 x1,y1,x2,y2
输出格式
只有1行:最短到达目的地距离
样例 #1
样例输入 #1
3
001
101
100
1 1 3 3
样例输出 #1
4
提示
20%数据:n<=100
100%数据:n<=1000
思路
bfs最短路+障碍
代码
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int n;
int X1, Y1, X2, Y2;
bool used[1010][1010];
int f[1010][1010];
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,-1,1 };
int g[1010][1010];
queue<pair<int, int>>q;
int main() {
memset(f, -1, sizeof(f));
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
char c; cin >> c;
g[i][j] = c - '0';
}
cin >> X1 >> Y1 >> X2 >> Y2;
used[X1][Y1] = true; f[X1][Y1] = 0;
q.push({ X1,Y1 });
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int xx = x + dx[i];
int yy = y + dy[i];
if (g[xx][yy] == 1 || used[xx][yy] || xx<1 || xx>n || yy<1 || yy>n)continue;
used[xx][yy] = true;
f[xx][yy] = f[x][y] + 1;
q.push({ xx,yy });
}
}
cout << f[X2][Y2] << endl;
}
标签:int,短路,中山路,yy,xx,离开,Y1,X1,1010 来源: https://www.cnblogs.com/wxy214/p/16358476.html