Oliver的救援
问题描述
在你的帮助下,Oliver终于追到小X了,可有一天,坏人把小X抓走了。这正是Oliver英雄救美的时候。所以,Oliver又找到哆啦A梦,借了一个机器,机器显示出一幅方格地图,它告诉Oliver哪里能走,哪里不能走,。时间紧急,Oliver想知道,最少要走多少个格子,才能找到小X。( 4 个方向)。
input
共 N+2 行,第一行为 N,第 N+2 行为 Oliver 和 小x 的坐标
以下N行N列0-1矩阵,1表示不能通过,0表示可以通过(左上角和右下角为0). N<=1000.
output
共一个数,为最少的走的格子数.
样例
输入
10
0100110100
0001110010
1000000001
1000100011
0000101100
1000001100
1001010011
0000010100
0101010000
1001000001
1 7 10 2
输出
14
问题分析
一个赤裸裸的广搜模板,最短路问题
P.S 输入要字符转数值
代码
#include<iostream>
#include<cstdio>
using namespace std;
char c;
int a[1010][1010],n,x1,x2,y1,y2,h,t;
int fx[5]={0,1,0,-1,0},fy[5]={0,0,1,0,-1};
struct c{
int x,y,s;
}s[1000010];
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
{
cin>>c;
a[i][j]=c-48; //输入字符转数值
}
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
s[1].x=x1; s[1].y=y1; s[1].s=0;
h=0; t=1;
do{
h++;
for (int i=1;i<=4;i++)
{
int xx=s[h].x+fx[i],yy=s[h].y+fy[i];
if (xx>0&&xx<=n&&yy>0&&yy<=n&&a[xx][yy]==0)
{
t++;
s[t].x=xx;
s[t].y=yy;
s[t].s=s[h].s+1;
a[xx][yy]=1; // 放入队尾,步数+1
if (xx==x2&&yy==y2)
{
cout<<s[t].s<<endl;
return 0;
}
}
}
}while(h<=t);
return 0;
}