【题目来源】
https://www.luogu.com.cn/problem/P1746
【题目描述】
爱与愁大神买完东西后,打算坐车离开中山路。现在爱与愁大神在 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 行,即最短到达目的地距离。
【输入样例】
3
001
101
100
1 1 3 3
【输出样例】
4
【数据范围】
对于 20% 数据,满足 1≤n≤100。
对于 100% 数据,满足 1≤n≤1000。
【算法分析】
BFS算法助记:建-入-量:头-出-入,详见:
https://blog.csdn.net/hnjzsyjyj/article/details/125801217
【算法代码】
cpp
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N=1e3+5;
char g[N][N];
int dis[N][N];
int dx[]= {-1,0,1,0};
int dy[]= {0,1,0,-1};
int n,m;
int bfs(int sx,int sy,int ex,int ey) {
memset(dis,-1,sizeof dis);
dis[sx][sy]=0;
queue<PII> q;
q.push({sx,sy});
while(!q.empty()) {
int x=q.front().first;
int y=q.front().second;
q.pop();
if(x==ex && y==ey) return dis[x][y];
for(int i=0; i<4; i++) {
int tx=x+dx[i];
int ty=y+dy[i];
if(tx>=0 && tx<n && ty>=0 && ty<m) {
if(g[tx][ty]!='1' && dis[tx][ty]==-1) {
dis[tx][ty]=dis[x][y]+1;
q.push({tx,ty});
}
}
}
}
return -1;
}
int main() {
cin>>n;
m=n;
for(int i=0; i<n; i++) {
cin>>g[i];
}
int sx,sy,ex,ey;
cin>>sx>>sy>>ex>>ey;
sx--,sy--,ex--,ey--;
cout<<bfs(sx,sy,ex,ey)<<endl;
return 0;
}
/*
in:
3
001
101
100
1 1 3 3
out:
4
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/158773523