DFS迷宫问题(c++)

题目描述

迷宫是一个二维矩阵,其中1为墙,0为路,3为入口,4为出口.要求从入口开始,从出口结束,按照 下,左,上,右 的顺序来搜索路径.

输入

迷宫宽度w 迷宫高度h
迷宫第一行
迷宫第二行

迷宫第h 行

输出

入口横坐标1 入口纵坐标1
横坐标2 纵坐标2
横坐标3 纵坐标3
横坐标4 纵坐标4

横坐标n-1 纵坐标n-1
出口横坐标n 出口纵坐标n

样例输入

8 10
1 1 1 1 1 1 1 1
1 0 1 1 0 1 0 1
1 0 1 0 0 1 0 1
1 1 0 3 1 0 1 1
1 0 0 1 0 0 4 1
1 0 0 0 0 1 1 1
1 0 1 0 0 1 0 1
1 0 1 0 0 0 1 1
1 1 1 1 0 0 0 1
1 1 1 1 1 1 1 1

样例输出

3 3
2 3
2 4
2 5
3 5
3 6
3 7
4 7
4 6
4 5
4 4
5 4
6 4

基本思路:这是一个非常经典的DFS的运用。DFS的思想就是一条路走到黑,然后往回走。

#include <iostream>
#include <cstdlib>
#include <stack>

using namespace std;

int dir[4][2] = {
	{1,0},//下
	{0,-1},//左
	{-1,0},//上
	{0,1}//右
};


int w, h, ex, ey, sx, sy;

struct Node {
	int x, y;
	Node() = default;
	Node(int X, int Y) : x(X), y(Y) {}
};

stack<Node> s, t;
int** map;
Node temp;

bool check(int x, int y) {
	if (x < h && x >= 0 && y >= 0 && y < w)
		return true;
	else return false;
}


bool DFS(int dh, int dw) {
	temp.x = dh;
	temp.y = dw;
	s.push(temp);
	if (dh == ex && dw == ey)//判断当前点是否是出口
		return true;


	for (int i = 0; i < 4; ++i) {//寻找当前点四个方向上的点
		int th = dh + dir[i][0], tw = dw + dir[i][1];
		if (check(th, tw) && map[th][tw] != 1) {//如果能走通,就一直走,
			map[dh][dw] = 1;//标记当前点
			if (DFS(th, tw))
				return true;
		}

	}
	s.pop();//如果四个方向都走不通,说明这个点是错误的,弹出栈。往回走
	return false;
}


int main() {
	cin >> w >> h;

	map = new int* [h];
	for (int i = 0; i < h; i++) map[i] = new int[w];

	for (int i = 0; i < h; ++i) {
		for (int j = 0; j < w; ++j) {
			cin >> map[i][j];
			if (map[i][j] == 3) {
				sx = i;
				sy = j;
			}
			if (map[i][j] == 4) {
				ex = i;
				ey = j;
			}
		}
	}

	DFS(sx, sy);

	while (!s.empty()) {
		Node iter;
		iter = s.top();
		t.push(iter);
		s.pop();
	}

	while (!t.empty()) {
		cout << t.top().y << " " << t.top().x << endl;
		t.pop();
	}

	return 0;
}

欢迎交流

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值