迷宫,返回所有路径并排序(C++)(回溯+dfs)

题意说明:要求给出一个m*n的矩阵迷宫,0代表入口,1代表道路,2代表墙体,3代表出口,要求返回从入口到出口的所有移动路径并按长短从小到大排序。

移动路径:就是wasd的移动路径,如一共走三步:下,右,下,则输出:sds。

代码如下:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
//0是入口,1是路,2是墙,3是出口,输入矩阵时输入数字 
class Maze {
public:
	string path;//记录wasd路径
	vector<string> ans;//最后未排序的答案
	vector<vector<bool>> check;//判断路是否来过
	int m, n;
	vector<string> test(vector<vector<int>> nums, int c, int v) {
		m = nums.size();
		n = nums[0].size();
		check = vector<vector<bool>>(m, vector<bool>(n, false));
        check[c][v] = true;
		dfs(nums, c, v);
		return ans;
	}
	void dfs(vector<vector<int>> nums, int x, int y) {
		if (nums[x][y] == 3) {
			ans.push_back(path);
			return;
		}
		//左
		if (y - 1 >= 0 && nums[x][y - 1] != 2) {
			if (check[x][y - 1] == false) {
				path.push_back('a');
				check[x][y - 1] = true;
				dfs(nums, x, y - 1);
				path.pop_back();
				check[x][y] = false;
			}
		}
		//右
		if (y + 1 < n && nums[x][y + 1] != 2) {
			if (check[x][y + 1] == false) {
				path.push_back('d');
				check[x][y + 1] = true;
				dfs(nums, x, y + 1);
				path.pop_back();
				check[x][y + 1] = false;
			}
		}
		//上
		if (x - 1 >= 0 && nums[x - 1][y] != 2) {
			if (check[x - 1][y] == false) {
				path.push_back('w');
				check[x - 1][y] = true;
				dfs(nums, x - 1, y);
				path.pop_back();
				check[x - 1][y] = false;
			}
		}
		//下
		if (x + 1 < m && nums[x + 1][y] != 2) {
			if (check[x + 1][y] == false) {
				path.push_back('s');
				check[x + 1][y] = true;
				dfs(nums, x + 1, y);
				path.pop_back();
				check[x + 1][y] = false;
			}
		}

	}
	//x-1>=0  x+1<n  y-1>=0  y+1<m
	//0入 1路 2阻 3出口
};

bool compare(string a, string b)
{
	return a.length() < b.length();
}
//排序函数


int main() {
	Maze a;
	cout << "传一个迷宫m*n" << endl;
	int m, n;
	int x, y;
	cin >> m >> n;
	cout << "输入数字矩阵迷宫,0是入口,1是路,2是墙,3是出口" << endl;
	vector<vector<int>> ret(m, vector<int>(n));
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			cin >> ret[i][j];
			if (ret[i][j] == 0) {
				x = i;
				y = j;
			}
		}
	}
	vector<string> ans = a.test(ret, x, y);
	m = ans.size();
	string kk[100];
	for (int i = 0; i < m; i++) {
		kk[i] = ans[i];
	}
	sort(kk, kk + m, compare);//排序
	cout << "最短的路是:" << kk[0] << endl;
	for (int i = 1; i < m; i++) {
		cout << kk[i] << endl;
	}
	return 0;
}

假设输入:4 4
1 0 1 3
1 2 2 1
1 2 2 1
1 1 1 1

得到的结果如图:

以上就是本文的所有内容,如果有帮助就点一个赞吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值