起点到终点的最少步数(广度优先搜索)

1. 问题描述:

给定一个n * m大小的迷宫,其中*代表不可通过的墙壁,而.代表平地,S表示起点,T表示终点,移动过程中,如果当前位置是(x,y)(下标从0开始),而且每次只能前往上下左右(x,y + 1)(x,y - 1)(x - 1,y)(x + 1,y)四个位置的平地,求从起点S到达终点T的最少步数

.....
.*.*.
.*S*.
.***.
...T*

2. 思路分析:

① 因为求解的最少步数,而且我们知道广度优先搜索可以用来求解最少步数的,所以我们可以使用广度优先来进行求解

② 从起点开始进行四个方向的广度优先搜索,最小到达终点的那么步数一定是最少的,所以在循环中我们每弹出一个节点那么进行坐标的判断,看一下是否等于了终点坐标,假如是的话那么直接返回弹出节点的记录的步数即可

③ 这道题目与之前使用广度优先检测联通块的题目是类似的,只是在前面的基础上增加一些代码即可解决

测试数据如下:

5 5
.....
.*.*.
.*S*.
.***.
...T*
2 2 4 3

输出结果是11

3. 下面是具体的代码:

#include<cstdio>
#include<queue>
#include<iostream>
using namespace std;
const int maxn = 100;
struct node{
	int x;
	int y;
	int step; 
}S, T, Node;//S为起点,T为终点,Node为临时节点 

int n, m;
char maze[maxn][maxn]; //迷宫信息 
bool inq[maxn][maxn] = {false};//记录是否入过队列 
int posx[4] = {0, 0, 1, -1};
int posy[4] = {1, -1, 0, 0};

bool test(int x, int y){
	if(x >= n || x < 0 || y >= m || y < 0)  return false;
	if(maze[x][y] == '*')  return false;
	if(inq[x][y] == true)  return false;
	return true;
}

int bfs(){
	queue<node> que;
	que.push(S);
	while(!que.empty()){
		node top = que.front();
		que.pop();
		if(top.x == T.x && top.y == T.y){
			return top.step;
		}
		for(int i = 0; i < 4; i++){
			int newx = top.x + posx[i];
			int newy = top.y + posy[i];
			if(test(newx, newy)){
				Node.x = newx;
				Node.y = newy;
				Node.step = top.step + 1;
				que.push(Node);
				inq[newx][newy] = true;
			} 
		}	
	}
}

int main(void){
	scanf("%d%d", &n, &m);
	for(int i = 0; i < n; ++i){
		getchar();
		for(int j = 0; j < m; ++j){
			maze[i][j] = getchar();
		}
		maze[i][m + 1] = '\0';
	}
	scanf("%d%d%d%d", &S.x, &S.y, &T.x, &T.y);
	printf("%d", bfs());
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值