五大常规算法---回溯法(判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以 从矩阵中任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。)


回溯法

: 利用的是深度遍历的思想,探索每一条路径。***

先从第一次节点开始,不断的探索,如果符合就沿着节点继续探索下去,所否退回上一个节点,探索上一个节点的其他路径。

例题:

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以
从矩阵中任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了
矩阵的某一格,那么该路径不能再次进入该格子。例如在下面的 3×4 的矩阵中包含一条字符串
“bfce”的路径(路径中的字母用下划线标出)。但矩阵中不包含字符串“abfb”的路径,因为 字符串的第一个字符 b
占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。 A B T G C F C S J D E H

解决方案:
本题解决的方法是,从矩阵第一个节点开始判断,如果第一个节点满足,就顺着第一个节点,判断字符串中的第二个是否满足,如果满足继续探索下去,不满足,退回上一级 。如果退回到第一个节点都不满足,那么再将第二个节点,设置为起始位置,开始判断。

#include<stdio.h>
#include<Windows.h>
#include<string>
using namespace std;
bool hasPath(const char*martix,int rows,int cols,const char* str);
bool hasPahthCore(const char* martix, int rows, int cols, int row, int col,
	int& length, const char* str, bool* visited);
int main() {
	const char* matrix1 = "ABTGCFCSJDEH"; 
	const char* str1 = "BFCE";
	const char* matrix2 = "ABTGCFCSJDEH";  //34
	const char* str2 = "ABFB";
	if (hasPath(matrix1, 3, 4, str1)) {
		printf("matrix1中找到了str1\n");
	}
	else {
		printf("matrix1中没有找到了str1\n");
	}
	if (hasPath(matrix2, 3, 4, str2)) {
		printf("matrix2中找到了str2\n");
	}
	else {
		printf("matrix2中没有找到了str2\n");
	}
	system("pause");
	return 0;
}
bool hasPath(const char* martix, int rows, int cols, const char* str) {
	if (martix == nullptr || rows < 1 || cols < 1 || str == nullptr) {
		return false;
	}
	bool* visited = new bool[rows * cols];
	memset(visited, 0, rows * cols);
	int length = 0;
	for (int i = 0;i < rows;i++) {
		for (int j = 0;j < cols;j++) {
			if (hasPahthCore(martix, rows, cols, i, j, length, str,visited)) {
				return true;
			}
		}
	}
	delete[] visited;
	return false;
}
bool hasPahthCore(const char* martix, int rows, int cols, int row, int col,
	int& length, const char* str,bool *visited) {
	if (str[length] == '\0') {
		return true;
	}
	bool path = false;
	if (row >= 0 && row < rows && col >= 0 && col < cols &&
		str[length] == martix[row * cols + col] &&
		!visited[row * cols + col]) {
		length++;
		visited[row * cols + col] = true;
		path = hasPahthCore(martix, rows, cols, col + 1, row, length, str, visited)
			|| hasPahthCore(martix, rows, cols, col - 1, row, length, str, visited)
			|| hasPahthCore(martix, rows, cols, col, row + 1, length, str, visited)
			|| hasPahthCore(martix, rows, cols, col, row - 1, length, str, visited);
		if (!path) {
			length--;
			visited[row * cols + col] = false;
		}
	}
	return path;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值