输出迷宫的所有路径 dfs

有一个nm格的迷宫(表示有n行、m列),其中有可走的也有不可走的,如果用1表示可以走,0表示不可以走,文件读入这nm个数据和起始点、结束点(起始点和结束点都是用两个数据来描述的,分别表示这个点的行号和列号)。现在要你编程找出所有可行的道路,要求所走的路中没有重复的点,走时只能是上下左右四个方向。如果一条路都不可行,则输出相应信息(用-l表示无路)。

第一行是两个数n,m( 1 < n , m < 15 ),接下来是m行n列由1和0组成的数据,最后两行是起始点和结束点
输入:
5 6
1 0 0 1 0 1
1 1 1 1 1 1
0 0 1 1 1 0
1 1 1 1 1 0
1 1 1 0 1 1
1 1
5 6

学深搜好累,自己写了一下

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

struct Point
{
	int px;
	int py;
};

int maze[20][20];
int r, c;
int dic[4][2] = {{1, 0}, {0, -1}, {-1, 0}, {0,1}};
int sx, sy;
int fx, fy;
int ans;
bool vis[20][20];
vector<Point> vec;

bool in(int x, int y)
{
	return x > 0 && y > 0 && x <= r && y <= c;
}

void Search(int x, int y)
{
	if(x == fx && y == fy){
		for(int i = 0; i < vec.size(); i++){
			cout << '(' << vec[i].px << ',' << vec[i].py << ')' << "->";
		}
		cout << '(' << fx << ',' << fy << ')' << endl;
		ans++;
		return;
	}
	
	
	for(int i = 0; i < 4; i++){
		int tx = x + dic[i][0];
		int ty = y + dic[i][1];
		if(in(tx, ty) && maze[tx][ty] && !vis[tx][ty]){
			vis[x][y] = true;
			Point a;
			a.px = x;
			a.py = y;
			vec.push_back(a);
			Search(tx, ty);
			vis[x][y] = false;
			vec.pop_back();
		}
	}
	return;
}

int main()
{
	cin >> r >> c;
	for(int i = 1; i <= r; i++){
		for(int j = 1; j <= c; j++)
			cin >> maze[i][j];
	}
	cin >> sx >> sy;
	cin >> fx >> fy;
	
	Search(sx, sy);
	
	if(ans == 0)
		cout << -1;
	return 0;
}
发布了4 篇原创文章 · 获赞 0 · 访问量 70

猜你喜欢

转载自blog.csdn.net/weixin_44284194/article/details/104202837