【BFS】Oliver的救援

Description

在你的帮助下,Oliver终于追到小X了,可有一天,坏人把小X抓走了。这正是Oliver英雄救美的时候。所以,Oliver又找到哆啦A梦,借了一个机器,机器显示出一幅方格地图,它告诉Oliver哪里能走,哪里不能走,。并且Oliver在这个地图的右下角,而小X在左上角。时间紧急,Oliver想知道,最少要走多少个格子,才能找到小X。(只能直走)。

Input

共N+1行,第一行为N,以下N行N列0-1矩阵,1表示不能通过,0表示可以通过(左上角和右下角为0). N<30.

Output

共一个数,为最少的走的格子数.

Sample Input

5
0 1 1 1 1
0 0 1 1 1
1 0 0 0 1
1 1 1 0 1
1 1 1 0 0

Sample Output

9


解题思路

板子广搜


正常程序

#include<iostream>
#include<cstdio>
using namespace std;
const int w[4][2]={{1,0},{0,-1},{-1,0},{0,1}};//方向
int a[2000][2000],s[2000][2000];//a是地图兼记录有没有走过,s是步数
int v[1001000][2],h,t=1;
int n,sx,sy,ex,ey;
bool check(int x,int y){
	return (x>0&&x<=n&&y>0&&y<=n);
}
void bfs(int x,int y){
	a[x][y]=s[x][y]=1;
	v[t][0]=x,v[t][1]=y;
	while(h++<t){
		for(int i=0;i<4;i++){
			int xx=v[h][0]+w[i][0],yy=v[h][1]+w[i][1];
			if(check(xx,yy)&&!a[xx][yy]){
				a[xx][yy]=1;
				s[xx][yy]=s[v[h][0]][v[h][1]]+1;
				v[++t][0]=xx,v[t][1]=yy;
				if(xx==1&&yy==1)return;
			}
		}
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	    for(int j=1;j<=n;j++)
		    scanf("%d",&a[i][j]);
	bfs(n,n); 
	printf("%d",s[1][1]);
}

但是不知道为什么数据出错了,所以改成了这样

#include<iostream>
#include<cstdio>
using namespace std;
const int w[4][2]={{1,0},{0,-1},{-1,0},{0,1}};
int a[2000][2000],s[2000][2000];
int v[1001000][2],h,t=1;
int n,sx,sy,ex,ey;
bool check(int x,int y){
	return (x>0&&x<=n&&y>0&&y<=n);
}
void bfs(int x,int y){
	a[x][y]=s[x][y]=1;
	v[t][0]=x,v[t][1]=y;
	while(h++<t){
		for(int i=0;i<4;i++){
			int xx=v[h][0]+w[i][0],yy=v[h][1]+w[i][1];
			if(check(xx,yy)&&!a[xx][yy]){
				a[xx][yy]=1;
				s[xx][yy]=s[v[h][0]][v[h][1]]+1;
				v[++t][0]=xx,v[t][1]=yy;
				if(xx==ex&&yy==ey)return;
			}
		}
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	    for(int j=1;j<=n;j++){
	    	char c;
	        cin>>c;
	        a[i][j]=c-48;
	    }//输入莫得空格
	scanf("%d%d%d%d",&sx,&sy,&ex,&ey);//莫名数据多了起点和终点
	bfs(sx,sy); 
	printf("%d",s[ex][ey]-1);
}
发布了45 篇原创文章 · 获赞 0 · 访问量 370

猜你喜欢

转载自blog.csdn.net/qq_39940018/article/details/103433062
BFS