电子老鼠闯迷宫【BFS】

21 篇文章 0 订阅

极短题干
D e s c r i p t i o n Description Description

找出一条自入口到出口最短路径。

I n p u t Input Input
12 //迷宫大小
2 9 11 8 //起点和终点
1 1 1 1 1 1 1 1 1 1 1 1 //邻接矩阵,0表示通,1表示不通
1 0 0 0 0 0 0 1 0 1 1 1
1 0 1 0 1 1 0 0 0 0 0 1
1 0 1 0 1 1 0 1 1 1 0 1
1 0 1 0 0 0 0 0 1 0 0 1
1 0 1 0 1 1 1 1 1 1 1 1
1 0 0 0 1 0 1 0 0 0 0 1
1 0 1 1 1 0 0 0 1 1 1 1
1 0 0 0 0 0 1 0 0 0 0 1
1 1 1 0 1 1 1 1 0 1 0 1
1 1 1 1 1 1 1 0 0 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
O u t p u t Output Output
(2,9)->(3,9)->(3,8)->(3,7)->(4,7)->(5,7)->(5,6)->(5,5)->(5,4)->(6,4)->(7,4)->(7,3)->(7,2)->(8,2)->(9,2)->(9,3)->(9,4)->(9,5)->(9,6)->(8,6)->(8,7)->(8,8)->(9,8)->(9,9)->(10,9)->(11,9)->(11,8)
27


广搜基础题

(我太菜了,改了三十分钟才改出来)。

几个注意点:

1.check函数要保证是对的。
2.for循环 0<i<4
3.队列headtail不要弄混。
4.方向数组不要码错

代码:

#include<iostream>
#include<cstdio>
using namespace std;
int n,cx,cy,ansy,ansx,s=0,last;
int a[1010][1010],st[1010][1010],fa[10101010];
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
void print(int x)
{
	if(x==0) return;
	s++;
	print(fa[x]);
	if(x!=last)
	  printf("(%d,%d)->",st[x][1],st[x][2]);
	else
	  printf("(%d,%d)\n",st[x][1],st[x][2]);
}
int check(int x,int y)
{
	if(x>=1&&x<=n&&y>=1&&y<=n)
	 {
	    if(a[x][y]==0)
	      return true;
     }
	  return false;
}
void bfs()
{
	int head=0,tail=1;
	st[1][1]=cx,st[1][2]=cy;
	fa[1]=0;
	a[cx][cy]=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];
	 	 	 	a[st[tail][1]][st[tail][2]]=1;
	 		    if(st[tail][1]==ansx&&st[tail][2]==ansy)
	 	 	 	 {
	 		 		last=tail;
	 		 		print(tail);
	 		 		cout<<s<<endl;
	 	 			tail=0;
	 		 		return;
	 	 	 	 }
	 	 	 }
	 	 }
	 }
}
int main()
{
	cin>>n;
	cin>>cx>>cy>>ansx>>ansy;
	for(int i=1; i<=n; i++)
	 for(int j=1; j<=n; j++)
	    cin>>a[i][j];
	bfs();
	return 0;
}

自我感觉广搜比深搜难

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值