离开中山路
题目背景
《爱与愁的故事第三弹·shopping》最终章。
题目描述
爱与愁大神买完东西后,打算坐车离开中山路。现在爱与愁大神在 x 1 , y 1 x_1,y_1 x1,y1 处,车站在 x 2 , y 2 x_2,y_2 x2,y2 处。现在给出一个 n × n ( n ≤ 1000 ) n \times n(n \le 1000) n×n(n≤1000) 的地图, 0 0 0 表示马路, 1 1 1 表示店铺(不能从店铺穿过),爱与愁大神只能垂直或水平着在马路上行进。爱与愁大神为了节省时间,他要求最短到达目的地距离(每两个相邻坐标间距离为 1 1 1)。你能帮他解决吗?
输入格式
第 1 1 1 行包含一个数 n n n。
第 2 2 2 行到第 n + 1 n+1 n+1 行:整个地图描述( 0 0 0 表示马路, 1 1 1 表示店铺,注意两个数之间没有空格)。
第 n + 2 n+2 n+2 行:四个数 x 1 , y 1 , x 2 , y 2 x_1,y_1,x_2,y_2 x1,y1,x2,y2。
输出格式
只有 1 1 1 行,即最短到达目的地距离。
样例 #1
样例输入 #1
3
001
101
100
1 1 3 3
样例输出 #1
4
提示
对于 20 % 20\% 20% 数据,满足 1 ≤ n ≤ 100 1\leq n \le 100 1≤n≤100。
对于 100 % 100\% 100% 数据,满足 1 ≤ n ≤ 1000 1\leq n \le 1000 1≤n≤1000。
思路
也就是用bfs求出最短次数(这个时候我们可以用结构体来存储)。
代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int N = 1010;
char s[N][N];
bool st[N][N];
struct E{
int x,y,cnt;
};
int n;
queue<E>q;
int stx,sty,edx,edy;
int ans;
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};
void bfs(int x,int y){
st[x][y]=true;
q.push({x,y,0});
while(q.size()){
E t=q.front();
q.pop();
int xx=t.x,yy=t.y,step=t.cnt+1;
for(int i=0;i<4;i++){
int a=xx+dx[i],b=yy+dy[i];
if(a<1||b<1||a>n||b>n||st[a][b]||s[a][b]=='1')continue;
st[a][b]=true;
if(a==edx&&b==edy){
ans=step;
return;
}
q.push({a,b,step});
}
}
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>s[i][j];
}
}
cin>>stx>>sty>>edx>>edy;
bfs(stx,sty);
cout<<ans;
return 0;
}