面试题12:矩阵中的路径

面试题12:矩阵中的路径

题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、上、下、右移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。

思路:利用回溯法解决该问题,采用递归的方式编码。

  1. 先判断某个格子是否是当前字符;
  2. 如果当前格子是当前字符,则进入3;如果不是,回退一个字符,进入3;
  3. 再判断该格子的左、上、下、右的格子是否是下一个字符;
  4. 重复进行第1、2、3,直到字符串访问结束;
  5. 引入访问变量记录已经走过的格子。

代码:

#include<iostream>

using namespace std;

bool hasPath(char* matrix, int rows,int cols,char* str);

bool hasPathCore(char* matrix, int rows, int cols, int row, int col, char* str, int pathLength, bool* visited);


int main()
{
	char* matrix = "abtgcfcsjdeh";
	char* str = "bfce";
	bool isHasPath = hasPath(matrix, 3, 4, str);
	if (isHasPath) {
		cout << "has path" << endl;
	}
	else {
		cout << "has no path" << endl;
	}
	
    return 0;
}

bool hasPath(char* matrix, int rows, int cols, char* str) {

	if (matrix == nullptr || str == nullptr || rows < 1 || cols < 1) {
		return false;
	}

	bool* visited = new bool[rows*cols];
	memset(visited, 0, rows*cols);
	int pathLength = 0;
	for (int i = 0; i < rows; i++) {
		for (int j = 0; j < cols; j++) {
			if (hasPathCore(matrix, rows, cols, i, j, str, pathLength, visited)) {
				return true;
			}
		}
	}

	delete visited;
	return false;
}

bool hasPathCore(char* matrix, int rows, int cols, int row, int col, char* str, int pathLength, bool* visited) {

	//匹配结束
	//提示,使用递归解决问题,必定先写结束条件
	if (str[pathLength] == '\0') {
		return true;
	}

	bool isHasPath = false;
	//判断当前字符
	if (row >= 0 && row < rows && cosl >= 0 && col < cols&&
		matrix[row*cols + col] == str[pathLength] && !visited[row*cols + col]) {
		
		visited[row*cols + col] = true;
		pathLength++;

		//判断周围字符
		isHasPath = hasPathCore(matrix, rows, cols, row + 1, col, str, pathLength, visited) ||
			hasPathCore(matrix, rows, cols, row - 1, col, str, pathLength, visited) ||
			hasPathCore(matrix, rows, cols, row, col + 1, str, pathLength, visited) ||
			hasPathCore(matrix, rows, cols, row, col - 1, str, pathLength, visited);

		if (!isHasPath) {
			visited[row*cols + col] = false;
			pathLength--;
		}

	}
	return isHasPath;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值