dfs回溯法

本文介绍了使用C++编写的两种算法:一种是利用回溯法解决迷宫中从起点到终点的最短步数问题,另一种是处理滑动问题,找到二维数组中每行最小值的递归方法。
摘要由CSDN通过智能技术生成

回溯法

走迷宫走的最短步数

#include <iostream>
#include <climits>
using namespace std;
char a[105][105];
int f[105][105];
int n, m, r, c;
int dx[4] = { 1 ,0 , -1, 0 };
int dy[4] = { 0 ,-1,0,1 };
void dfs(int x, int y, int tep) {
	if (f[x][y] > tep) {
		f[x][y] = tep;
		for (int i = 0; i < 4; i++) {
			int xx = x + dx[i], yy = y + dy[i];
			if (a[xx][yy] == '.') {
				dfs(xx, yy, tep + 1);
			}
		}
	}
}
int main()
{
	cin >> n >> m >> r >> c;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> a[i][j];
			f[i][j] = INT_MAX;
		}
	}
	dfs(1, 1, 1);
	cout << f[r][c];
	return 0;
}

滑行问题

#include <iostream>
#include <climits>
#include <algorithm>
using namespace std;
int a[105][105], f[105][105];
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };
int n, m, ans = 0;
int dfs(int x, int y) {
	if (f[x][y] != 0)
		return f[x][y];
	int t = 0;
	f[x][y] = 1;
	for (int i = 0; i < 4; i++) {
		int xx = x + dx[i], yy = y + dy[i];
		if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && a[xx][yy] < a[x][y]) {
			t = dfs(xx, yy) + 1;
		}
		f[x][y] = max(t, f[x][y]);
	}
	return f[x][y];
}
int main()
{
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> a[i][j];
		}
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			f[i][j] = dfs(i, j);
			ans = max(ans, f[i][j]);
		}
	}
	cout << ans;
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值