2020-4-5穿越雷区(bfs)

该博客介绍了一个使用宽度优先搜索(BFS)算法解决穿越雷区问题的C++实现。通过输入一个二维矩阵表示雷区地图,找出从起点A到终点B的最短路径。代码中定义了节点结构体,利用队列进行BFS遍历,并通过判断相邻格子是否可通行来更新路径。当找到终点B时,输出路径长度。
摘要由CSDN通过智能技术生成

穿越雷区(bfs)



```cpp
#include<bits/stdc++.h>
using namespace std;

int n,x,y;
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int vis[111][111]={0};
char maze[111][111];

struct node{
	int x;
	int y;
	string fu;
//	int step;
};
node q[1000];

bool judge(node temp,int tx,int ty)
{
	if(vis[tx][ty]||maze[tx][ty]==maze[temp.x][temp.y])
	return true;
	else
	return false;
}


bool bfs()
{
	int front=0,end=0;
	node s,t,next;
	s.x=x;
	s.y=y;
//	s.step=0;
	s.fu="A";
	vis[x][y]=1;
	q[end++]=s;
	while(front<end)
	{
		t=q[front];
		front++;
//		cout<<t.x<<t.y<<maze[t.x][t.y]<<t.step<<endl;
		for(int i=0;i<4;i++)
		{
			int dx=t.x+dir[i][0];
			int dy=t.y+dir[i][1];
			if(maze[dx][dy]=='B')
			{
				cout<<t.fu.length()<<endl;
				return true;
			}
			if(dx<0||dx>=n||dy<0||dy>=n)continue;
			if(judge(t,dx,dy))continue;
			vis[dx][dy]=1;
			next.x=dx;
			next.y=dy;
//			next.step=t.step++;	
			next.fu=t.fu+maze[dx][dy];	
			q[end++]=next;	
		}
	}
	return false;
	
}

int main()
{
	cin>>n;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++)
		{
			cin>>maze[i][j];
			if(maze[i][j]=='A')
			{
				x=i;
				y=j;
			}
		}
	}
	if(!bfs())cout<<-1<<endl;
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值