Oliver的救援【BFS】

21 篇文章 0 订阅

原题链接传送门
D e s c r i p t i o n Description Description

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

I n p u t Input Input

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

O u t p u t Output Output

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

S a m p l e I n p u t Sample Input SampleInput

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

S a m p l e O u t p u t Sample Output SampleOutput

9
———————————————————————————————————————————————

这题。。。

不就是电子老鼠闯迷宫吗!

在这里插入图片描述
然后copy提交,恭喜WA。
检查到死检查不出来。
发现老师数据放错了QAQ。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int a[1010][1010],fa[1000010],st[1000010][5];
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
int n,y1,y2,x1,x2;
int check(int x,int y)
{
	if(x>0&&x<=n&&y>0&&y<=n)
	 {
	 	if(a[x][y]==0)
	 	  return true;
	 }
	return false;
}
void bfs()
{
	int head=0,tail=1;
	st[1][1]=x1,st[1][2]=y1,st[1][3]=0;
	fa[1]=0,a[n][n]=1;
	while(head<=tail)
	 {
	 	head++;
	 	for(int i=0; i<4; i++)
	 	 {
	 	 	if(check(st[head][1]+dx[i],st[head][2]+dy[i])==1)
	 	 	 {
	 	 	 	tail++;
	 	 	 	fa[tail]=head;
	 	 	 	st[tail][1]=st[head][1]+dx[i];
	 	 	 	st[tail][2]=st[head][2]+dy[i];
	 	 	 	st[tail][3]=st[head][3]+1;
	 	 	 	a[st[tail][1]][st[tail][2]]=1;
	 	 	 	if(st[tail][1]==x2&&st[tail][2]==y2)
	 	 	     {
	 	 	 	   cout<<st[tail][3];
	 	 	 	   return;
	 	 	     } 
	 	 	 }
	 	 }
	 }
}
int main()
{
	scanf("%d",&n);
	for(int i=1; i<=n; i++)
	 for(int j=1; j<=n; j++)
	    scanf("%1d",&a[i][j]);
	cin>>x1>>y1>>x2>>y2;
	bfs();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值