矩阵中的路径(回溯法)

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

解题思路:
      我们可以用回溯法解决这个问题。首先在矩阵中任选一个格子作为路径的起点。假设矩阵中某个格子的字符为ch,并且这个格子将对应于路径上的第i个字符。如果路径上的第i个字符不是ch,那么这个格子不可能处在路径上的第i个位置。如果路径上的第i个字符正好是ch,那么到相邻的格子寻找路径上的第i+1个字符。除矩阵边界上的格子之外,其他格子都有4个相邻的格子。重复这个过程,直到路径上的所有字符都在矩阵中找到相应的位置。

      由于回溯法的递归特性,路径可以被看成一个栈。当在矩阵中定位了路径中前n个位置之后,在与第n个字符对应的格子的周围都没有找到第n+1个字符,这时候只好在路径上回到n-1个字符,重新定位第n个字符。

      由于路径不能重复进入矩阵的格子,所以还需要定义和字符矩阵大小一样的布尔值矩阵,用来标记路径是否已经进入了每个格子。

代码如下:

# include<iostream>
using namespace std;

bool hasPathCore(const char* matrix, int rows, int cols, 
	             int row, int col, const char* str, 
				 int& pathLength, bool* visited)
{
	if (str[pathLength] == '\0')//当字符串已经匹配到末尾时,说明已经找到完全匹配的路径,因此返回true
	{
		return true;
	}
	bool hasPath = false;
	if (row >= 0 && row < rows && col >= 0 && col < cols
		&& matrix[row * cols + col] == str[pathLength]
		&& !visited[row * cols + col])
	{
		++pathLength;
		visited[row * cols + col] = true;
                //当矩阵中坐标为(row, col)的格子和路径字符串中下标为pathLength的字符一样时,
                //从4个相邻的格子中去定位路径字符串中下标为pathLength+1的字符
		hasPath = 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)
			|| hasPathCore(matrix, rows, cols, row + 1, col,
			str, pathLength, visited);
                //如果4个相邻的格子都没有匹配字符串中下标pathLength+1的字符,
                //则表明当前路径字符串中下标为pathLength的字符在矩阵中的定位不正确,
                //我们需要回到前一个字符(pathLength-1),然后重新定位
		if (!hasPath)
		{
			--pathLength;
			visited[row * cols + col] = false;
		}
	}
	return hasPath;
}
bool hasPath(char* matrix, int rows, int cols, char* str)
{
	/*
	* matrix参数表示矩阵
	* rows表示矩阵的行
	* cols表示矩阵的列
	*/
	if (matrix == NULL || rows < 1 || cols < 1 || str == NULL)
	{
		return false;
	}

	bool *visited = new bool[rows * cols];//定义标记路径的布尔矩阵
	memset(visited, 0, rows * cols);

	int parhLength = 0;//定义已经匹配路径的长度
	for (int row = 0; row < cols; ++row)//从第一个格子开始寻找有无路径匹配
	{
		for (int col = 0; col < cols; ++col)
		{
			if (hasPathCore(matrix, rows, cols, row, col, str, parhLength, visited))
			{
				return true;
			}
		}
	}
	delete[] visited;
	return false;
}
int main()
{
	char matrix[] = { 'a', 'b', 't', 'g',
		'c', 'f', 'c', 's',
		'j', 'd', 'e', 'h' };
	int result = hasPath(matrix, 3, 4, "bfce");
	cout << result << endl; 
	int result1 = hasPath(matrix, 3, 4, "bbce");
	cout << result1 << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41727218/article/details/87826753