剑指offfer面试题12---矩阵中的路径

运用之前博客中学习的回溯算法比较容易解决

值得学习的知识点:

(1)动态内存的建立释放,其中的bool *visited = new bool[rows*cols];     delete[] visited; //动态内存不用了的话要释放

      memset()用法(动态内存刚分配时候初始化用)

(2)怎样用一个字符串好指针打配,让它表示起来给人以二维数组的形象感

        char* Matrix = "abtgcfcsjdeh";matrix[row*cols + col](相当于matrix[row][col])

(3)什么时候函数的形参要加引用符号?

    当对应的实参在函数内值会被该别且不希望由此改变实参值得时候,比如此例中的pathlength,因为我们希望

    在Backtrack()遍历矩阵的时候,如果当前点不适合,走下个点时,pathlength还是初始时定义的0

(3)复习回溯算法的基本套路

代码:

#include <iostream>
using namespace std;

bool Backtrack(char* matrix, int row, int col, int rows, int cols, char*str, int& pathlength, bool* visited)
{
	
	if (str[pathlength] == '\0')
		return true;

	bool haspath = false;

		if (rows >= 0 && row < rows&&col < cols&&matrix[row*cols + col] == str[pathlength] && !visited[row*cols + col])
		{
			pathlength++; visited[row*cols + col] = true;

			haspath = (Backtrack(matrix, row + 1, col, rows, cols, str, pathlength, visited) ||
				Backtrack(matrix, row - 1, col, rows, cols, str, pathlength, visited) ||
				Backtrack(matrix, row, col - 1, rows, cols, str, pathlength, visited) ||
				Backtrack(matrix, row, col + 1, rows, cols, str, pathlength, visited));


			pathlength--; visited[row*cols + col] = false;
		}
	
		
	return haspath;
}
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;
	for (int i = 0; i <= rows - 1; ++i)
	{
		for (int j = 0; j <= cols-1; ++j)
		{
			if (Backtrack(matrix, i, j, rows, cols, str, pathlength, visited) == true)
			{
				delete[] visited;
				return true;
			}
		}
	}
	delete[] visited;
	return false;
}

int main()
{
	char* Matrix = "abtgcfcsjdeh";
	char* str = "bfce";
	cout << hasPath(Matrix, 3, 4, str);

	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_34793133/article/details/80779693