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

迷宫:

S****
*###*
*###*
*###*
****T

升级版:找到迷宫中的路径数目  path number  并输出路径以及路径数

 

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

//输入一个地图,然后找出口


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

		return;

	}
	
		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循环在,第一次被访问的路径中的i再次访问时不可能再次访问同一个方向了,i++了,只能访问其他方向了。
		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) {
				vis[tx][ty] == true;
				dfs(tx, ty, step + 1);
				cout <<x << "," << y << endl;
				vis[tx][ty] == false;
				

			}
		}
		vis[x][y] == 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;
				dfs(x, y, 0);
					cout << "找到出口啦" << endl;
				
				
			}


		}
	}

 }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值