迷宫问题并求最短路径

#include <iostream>
#include <cassert>
#include <stack>
#include <vector>

struct Pos
{
	int _row;
	int _col;
};

bool MinPath(vector<vector<int>>& maze, int row, int col, Pos enrty, stack<Pos>& minPath)
{
	assert(!maze.empty());
	stack<Pos> path;
	bool firstOrNo = true;
	vector<vector<int>> tmp = maze;
	while (maze[enrty._row][enrty._col] != 3)
	{
		tmp = maze;
		path.push(enrty);
		while (!path.empty())
		{
			Pos cur = path.top();
			tmp[cur._row][cur._col] = 2;
			if (path.top()._row == row - 1)
			{
				maze[path.top()._row][path.top()._col] = 4;
				if (firstOrNo || path.size() < minPath.size())
				{
					minPath = path;
					firstOrNo = false;
				}
				while (!path.empty())
				{
					path.pop();
				}
				break;
			}
			//上
			Pos next = cur;
			next._row--;
			if (next._row >= 0 && next._row < row
				&&next._col >= 0 && next._col < col
				&&tmp[next._row][next._col] == 0)
			{
				path.push(next);
				continue;
			}
			//下
			next = cur;
			next._row++;
			if (next._row >= 0 && next._row < row
				&&next._col >= 0 && next._col < col
				&&tmp[next._row][next._col] == 0)
			{
				path.push(next);
				continue;
			}
			//左
			next = cur;
			next._col--;
			if (next._row >= 0 && next._row < row
				&&next._col >= 0 && next._col < col
				&&tmp[next._row][next._col] == 0)
			{
				path.push(next);
				continue;
			}
			//右
			next = cur;
			next._col++;
			if (next._row >= 0 && next._row < row
				&&next._col >= 0 && next._col < col
				&&tmp[next._row][next._col] == 0)
			{
				path.push(next);
				continue;
			}
			maze[path.top()._row][path.top()._col] = 3;
			path.pop();
		}//while !empty(path)

	} //while 大

	//在地图中标出最短路径
	stack<Pos> p = minPath;
	while (!p.empty())
	{
		maze[p.top()._row][p.top()._col] = 2;
		p.pop();
	}
	
	return !minPath.empty();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值