迷宫问题完整版:寻找出口的方案+最短路径的距离+最短路径

 DFS解决下述所有问题:

寻找出口的方案个数+最短路径的距离+最短路径坐标

#include<iostream>
#include<vector>
using namespace std;
vector<pair<int, int>>ans;
vector<pair<int, int>>temp;
int row, col;
int num;
int minstep = 99999;
int step = 0;//距离
int path = 0;//方案总数
int dx[] = { 0,0,-1,1 };
int dy[] = { 1,-1,0,0 };

vector<vector<int>>v;
vector<vector<int>>a(100,vector<int>(100,0));
void dfs(int x,int y,int step)
{
	temp.push_back({ x,y });
	if (x == row - 1 && y == col - 1)
	{
		path++;
		ans = temp;
		if (step < minstep)
		{
			minstep = step;
		}
		return;//找到了就结束
	}
	for (int k = 0; k < 4; k++)
	{
		int tx = x + dx[k];
		int ty = y + dy[k];
		if (tx<0 || ty<0 || tx>row - 1 || ty>col - 1 || v[tx][ty] == 1 || a[tx][ty] == 1)
			continue;
		a[tx][ty] = 1;
		dfs(tx, ty, step + 1);
		temp.pop_back();//没找到就回溯
		a[tx][ty] = 0;
	}
	return;
}
int main()
{
	while (cin >> row >> col)
	{
		for (int i = 0; i < row; i++)
		{
			vector<int>v1(col,0);
			for (int j = 0; j < col; j++)
			{
				cin >> v1[j];
			}
			v.push_back(v1);
		}
		a[0][0] = 1;
		dfs(0,0,step);
		cout << path << endl;
		cout << minstep << endl;
		for (auto t : ans)
			cout <<"(" <<t.first<<","<<t.second<<")" << endl;
	}
	return 0;
}

结果展示:

                                                  

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值