剑指offer面试题12:矩阵中的路径(回溯法的应用)【C++版本】

题目:

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

解题思路:

可以用回溯法来解决的典型问题。

用回溯法解决问题的所有选项都可以形象的用树状结构表示。

在某一步有n个可能的选项,那么该步骤可以看做是树状结构中的一个节点,每个选项看成树中节点连接线,经过这些连接线到达该节点的n个子节点。树的叶子节点对应着终结状态。如果树的叶节点满足题目的约束条件,那么我们就找到了一个可行的解决方案。 
如果叶节点的状态不满足约束条件,那么只好回溯到它的上一个节点再尝试其他的选项。如果上一个节点的所有可能选项都已经试过了,并且不能到达满足约束条件的终结状态。则再次回溯到上一个节点。

通常回溯法比较适合用递归实现。

解题注意事项:

1.用一个对应的布尔值矩阵来记录矩阵中已经访问过的位置 
2.在使用递归的时候应该注意,在退出递归的时候需要根据需求对计数和标志进行回退、清除等操作。

【代码如下】

class Solution {
public:
	bool hasPath(char* matrix, int rows, int cols, char* str)
	{
		//首先要考察这个算法的鲁棒性
		if (matrix == nullptr | rows < 1 || cols < 1 || str == nullptr)
			return false;
 
		bool* visited = new bool[rows*cols]; //格子是否被访问过
		memset(visited, 0, rows*cols);
 
		int pathLength = 0;//路径字符串的下标pathLength
 
		for (int row = 0; row < rows; row++)
			for (int col = 0; col < cols; col++)
				if (hasPathCore(matrix, rows, cols, row, col, str, pathLength, visited))
					return true;
		delete[] visited;
		return false;
 
	}
	bool hasPathCore(const char* matrix, int rows, int cols, int row, int col, const char* str, int& pathLength, bool *visited)
	{
		if (str[pathLength] == '\0')
			return true;
		bool hasPath = false;
 
		if (row >= 0 && row < rows&&col >= 0 && col < cols &&str[pathLength] == matrix[row*cols + col] && !visited[row*cols + col])
		{
			pathLength++;
			visited[row*cols + col] = true;
			hasPath = 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 - 1, col, str, pathLength, visited)
				|| hasPathCore(matrix, rows, cols, row, col - 1, str, pathLength, visited);
			if (!hasPath)
			{
				pathLength--;
				visited[row*cols + col] = false;
			}
 
		}
		return hasPath;
	}
};

猜你喜欢

转载自blog.csdn.net/zpznba/article/details/87938627