3752走迷宫(bfs)

博客围绕迷宫问题展开,给定由空地和障碍物组成的R行C列迷宫,要求从左上角走到右下角的最少步数,只能水平或垂直移动。给出了输入输出格式及示例,最后提出能否用DFS解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述
一个迷宫由R行C列格子组成,有的格子里有障碍物,不能走;有的格子是空地,可以走。
给定一个迷宫,求从左上角走到右下角最少需要走多少步(数据保证一定能走到)。只能在水平方向或垂直方向走,不能斜着走。

Input
第一行是两个整数,R和C,代表迷宫的长和宽。( 1<= R,C <= 40)
接下来是R行,每行C个字符,代表整个迷宫。
空地格子用’.’表示,有障碍物的格子用’#’表示。
迷宫左上角和右下角都是’.’。
Output
输出从左上角走到右下角至少要经过多少步(即至少要经过多少个空地格子)。计算步数要包括起点和终点。
Sample Input

5 5
…###
#…
#.#.#
#.#.#
#.#…

Sample Output
9

#include<iostream>
#include<queue>
using namespace std;
char aa[100][100];
int dir[4][2]={-1,0,1,0,0,-1,0,1};
int vis[100][100]={0};
int m,n;

typedef struct NODE{
	int x;
	int y;
	int step;
}node;

int bfs(int a,int b){
	node temp,next;
	temp.x=a;
	temp.y=b;
	temp.step=1;
	vis[temp.x][temp.y]=1;
	queue<node> q;
	q.push(temp);
	while(!q.empty()){	
		temp=q.front();
		q.pop();
		for(int i=0;i<4;i++){
			next.x=temp.x+dir[i][0];
			next.y=temp.y+dir[i][1];
			next.step=temp.step+1;
			if(next.x<0 || next.y<0 ||next.x>m || next.y>n ||vis[next.x][next.y]==1 ||aa[next.x][next.y]=='#'){
				continue;
			}
			if(next.x==m-1 &&next.y==n-1){
				return next.step;
			}
			vis[next.x][next.y]=1;
			q.push(next);
		}
		
	}
}



int main(){

	cin>>m>>n;
	
	for(int i=0;i<m;i++){
		for(int j=0;j<n;j++){
			cin>>aa[i][j];
		}
	}	
	int ans=bfs(0,0);
	cout<<ans;
	
	
	return 0;
}

ask
?能否用 dsf解决?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值