1252 走迷宫

#include<bits/stdc++.h>
using namespace std;
int dx[4]={0,1,-1,0};
int dy[4]={1,0,0,-1};
int r,cc;
char c[2005][2005];
int vit[2005][2005];
struct node{
	int x;//行 
	int y;//列 
	int step;//步数
}a[2005];
void bfs(){
	int h=1,t=1;//h头t尾 
	while(h<=t){
		for(int i=0;i<=3;i++){
			int xx=a[h].x+dx[i];
			int yy=a[h].y+dy[i];
			if(c[xx][yy]=='.'&&vit[xx][yy]==0&&xx>0&&xx<=r&&yy>0&&yy<=cc){
				//cout<<xx<<" "<<yy<<" "<<a[h].x<<" "<<a[h].y<<endl;
				vit[xx][yy]=1;
				t++;
				a[t].x=xx;
				a[t].y=yy;
				a[t].step=a[h].step+1;
				if(a[t].x==r&&a[t].y==cc){
					cout<<a[t].step<<endl;
					return;
				}
			}
		}
		h++;
	}
}
int main(){
	cin>>r>>cc;
	for(int i=1;i<=r;i++){
		for(int j=1;j<=cc;j++){
			cin>>c[i][j];
		}
	}
	a[1].x=a[1].y=a[1].step=1;
	vit[1][1]=1;
	bfs();
	return 0;
}

看了源代码 我是一片懵,因为这次的代码用到了结构体 struct 他可以把变量撞到一个数组里面,在调用时数组的一项可以有多项数据,十分 nice.

struct node{
	int x;//行 
	int y;//列 
	int step;//步数
}a[2005];

        再用上宽搜 bfs,他就是把数依次存入队列中遍历,无需回溯,速度飞快,而头超过尾时便遍历结束输出。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值