题目背景
《爱与愁的故事第三弹·shopping》最终章。
题目描述
爱与愁大神买完东西后,打算坐车离开中山路。现在爱与愁大神在 x_1,y_1x1,y1 处,车站在 x_2,y_2x2,y2 处。现在给出一个 n \times n(n \le 1000)n×n(n≤1000) 的地图,00 表示马路,11 表示店铺(不能从店铺穿过),爱与愁大神只能垂直或水平着在马路上行进。爱与愁大神为了节省时间,他要求最短到达目的地距离(每两个相邻坐标间距离为 11)。你能帮他解决吗?
输入格式
第 11 行包含一个数 nn。
第 22 行到第 n+1n+1 行:整个地图描述(00 表示马路,11 表示店铺,注意两个数之间没有空格)。
第 n+2n+2 行:四个数 x_1,y_1,x_2,y_2x1,y1,x2,y2。
输出格式
只有 11 行,即最短到达目的地距离。
输入输出样例
输入 #1复制
3
001
101
100
1 1 3 3
输出 #1复制
4
说明/提示
对于 20\%20% 数据,满足 1\leq n \le 1001≤n≤100。
对于 100\%100% 数据,满足 1\leq n \le 10001≤n≤1000。
思路
最短路径,用bfs
注意一下输入没有用空格分割,所以使用字符数组用cin输入,不需要考虑空格
#include<iostream>
#include "math.h"
#include "algorithm"
#include "queue"
using namespace std;
char array[1001][1001];
bool book[1001][1001];
int d[1001][1001];
int dx[4] = {-1, 1, 0,0 };
int dy[4] = {0, 0, -1,1 };
int main() {
int n,x0,y0,x1,y1;
char str;
cin>>n;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin>>array[i][j];
if (array[i][j]=='1'){
book[i][j]= true;
}
}
}
cin>>x0>>y0>>x1>>y1;
queue<pair<int,int>>q;
q.push(make_pair(x0-1,y0-1));
book[x0-1][y0-1]= true;
while(!q.empty()){
int tx=q.front().first,ty=q.front().second;
q.pop();
for (int i = 0; i < 4; ++i) {
if ((tx+dx[i]>=0&&tx+dx[i]<n) &&(ty+dy[i]>=0&&ty+dy[i]<n) && !book[tx+dx[i]][ty+dy[i]]){
q.push(make_pair(tx+dx[i],ty+dy[i]));
book[tx+dx[i]][ty+dy[i]]= true;
d[tx+dx[i]][ty+dy[i]]=d[tx][ty]+1;
}
}
}
cout<<d[x1-1][y1-1];
return 0;
}