迷宫问题——深度优先搜索与回溯

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

//输入一个地图,然后找出口
//S**##
//*#*##
//##*##
//##**#
//##**T

char maze[20][20];
   bool vis[20][20];
   int n, m;
   int dir[2][4] = { {1,0,-1,0},
   {0,-1,0,1 } };
bool dfs(int x, int y,int step) {
	if (maze[x][y] == 'T') {
		cout << step << endl;
		cout << x << "," << y << endl;
		return true;

	}
	
		vis[x][y] = true;

		/*
		int tx = x + 1;
		int ty = y;
		if (tx >= 0 && tx < m && ty >= 0 && ty < n && maze[tx][ty] != '#' && vis[tx][ty] == false) {
			if(dfs(tx, ty,step+1))
			return true;
		}
		 tx = x;
		 ty = y - 1;
		if (tx >= 0 && tx < m && ty >= 0 && ty < n && maze[tx][ty] != '#' && vis[tx][ty] == false) {
			if(dfs(tx, ty,step+1))
			return true;
		}
		 tx = x - 1;
		 ty = y;
		if (tx >= 0 && tx < m && ty >= 0 && ty < n && maze[tx][ty] != '#' && vis[tx][ty] == false) {
			if(dfs(tx, ty,step+1))
			return true;
		}
		 tx = x;
		 ty = y + 1;
		if (tx >= 0 && tx < m && ty >= 0 && ty < n && maze[tx][ty] != '#' && vis[tx][ty] == false) {
			if(dfs(tx, ty,step+1))
			return true;
		}

		//上下左右都不能走的话回退
		*/
		int tx = 0;
		int ty = 0;
		
		for (int j = 0; j < 4; j++) {
			tx = x + dir[0][j];
			ty = y + dir[1][j];

			if (tx >= 0 && tx < n && ty >= 0 && ty < m && maze[tx][ty] != '#' && vis[tx][ty] == false) {
				if (dfs(tx, ty, step + 1))
					cout << x << "," << y << endl;
					return true;
			}
		}
		
		vis[x][y] == false;

		return false;
}


int main() {
	
	
	
	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cin >> maze[i][j];
			vis[i][j] = false;

		}

	}
	int x, y;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			 
			if (maze[i][j] =='S') {
				x = i;
				y = j;
				if (dfs(x, y,0) ){
					cout << "找到出口啦" << endl;
				}
				else
					cout << "lose" << endl;
			}


		}
	}


 }

从S开始,到T为迷宫的出口 ,在一个n*m大小的迷宫内搜索出口

代码思路:一开始从字符为S的位置开始遍历,从每个坐标的右,下,左,上的顺序依次遍历

一开始是dfs(0,0,0),之后在dfs(0,0,0)中调用dfs(0,1,1),再在dfs(0,1,1)中调用dfs(0,2,2),

一直递归调用到dfs(4,4,8)出口的位置,输出dfs(4,4,8)的函数返回值,由于dfs,(4,3,7)调用的dfs(4,4,8)所以紧接着才输出的方式(4,3,7)的返回值,依次如下

8

4,4
4,3
4,2
3,2
2,2
1,2
0,2
0,1
0,0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值