矩阵走迷宫:BFS

1、矩阵走迷宫问题描述

       给定一个只有 0 和 1 的矩阵,0 代表障碍物,1 代表可以通过。求从起点 B 到终点 E 的最短路径。

输入:

       第一行:两个数字 n 、m,代表矩阵大小;

       接下来 n 行:代表矩阵输入;

       接下来一行:代表起点坐标;

       最后一行:代表终点坐标。

输出:

       从起点到终点的最短路径。

       如果路径不存在,则输出-1;如果存在,则输出最短路径长度。

2、敲代码

(1)思路

       BFS,访问过的就标记为障碍,每一次从4个方向找一个没有障碍的进队。最终层数就是最短路径。

(2)

/*

输入
	4 5
	1 0 1 1 1
	1 0 1 0 1
	1 1 1 0 1
	0 0 0 0 1
	0 0
	3 4
输出
	12


输入
	4 5
	1 0 1 1 1
	1 0 1 0 1
	1 1 1 0 1
	0 0 0 0 1
	2 1
	3 4
输出
	9
*/

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int main() {

	//input
	int n, m;
	cin >> n >> m;
	vector<vector<int>> nums(n, vector<int>(m));
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cin >> nums[i][j];


	int bx, by;         //起点
	int ex, ey;         //终点
	cin >> bx >> by;
	cin >> ex >> ey;

	//起点终点判断
	if (nums[bx][by] == 0 || nums[ex][ey] == 0){
		cout << -1 << endl;
		return 0;
	}

	//bfs
	queue<pair<int, int>> q;
	q.push({ bx, by });      //起点进队
	nums[bx][by] = 0;        //已访问,设为障碍

	int cnt = 0;
	static int a[5] = { 0, 1, 0, -1, 0 };

	while (!q.empty()) {
		int qs = q.size();
		cnt++;

		while (qs--) {
			auto qf = q.front();
			q.pop();
		
			for (int i = 0; i < 4; i++) {
				int x = qf.first + a[i];
				int y = qf.second + a[i + 1];

				if (x < 0 || x >= n || y < 0 || y >= m) continue;    //越界
				if (nums[x][y] == 0) continue;                       //障碍

				//终点
				if (x == ex && y == ey) {
					cout << cnt + 1;                   //加1,包括起点;不加1,不包括起点
					return 0;
				}

				q.push({ x, y });      //进队
				nums[x][y] = 0;        //访问标记
			}
		}
	}

	cout << -1 << endl;
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值