[Question] P89 Sword refers to offer: Backtracking method: Interview question 12: Path in the matrix (detailed explanation)

Interview Question 12: Paths in the Matrix
Please design a function to determine whether there is a path that contains all the characters of a string in a matrix.
The path can start from any grid in the matrix, and each step can move one grid to the left, right, up, and down in the matrix. If a path passes through a grid of the matrix, then the path cannot enter the grid again.

Insert picture description here

#include <cstdio>
#include <string>
#include <stack>
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')
		return true;
	// 判断当前矩阵字符前,先将hasPath置为false
	bool hasPath = false;
	// 此时路径字符串上待判断的字符 == 当前矩阵字符 且 当前矩阵字符没有被使用
	if (row >= 0 && row < rows && col >= 0 && col < cols
		&& matrix[row * cols + col] == str[pathLength]
		&& !visited[row * cols + col])
	{
    
    
		// 开始遍历路径字符串上下一个字符
		++pathLength;
		// 将刚才已确定的字符在布尔值矩阵置为true,防止下次遍历被重复使用
		visited[row * cols + col] = true;
		// 围绕着当前已确定的字符,开始判断上下左右四个方向新的矩阵字符
		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);
		// hasPath==0:已确定的字符的上下左右四个方向新的矩阵字符均不符合要求
		// 证明当前路径不符合要求
		// 只能回退到上一个字符重新遍历
		if (!hasPath)
		{
    
    
			--pathLength;
			visited[row * cols + col] = false;
		}
	}

	return hasPath;
}

bool hasPath(const char* matrix, int rows, int cols, const 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;
	// 以矩阵中每一个字符为起点而产生的路径与str进行匹配
	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;
}

void Test(const char* testName, const char* matrix, int rows,
		  int cols, const char* str, bool expected)
{
    
    
	if (testName != nullptr)
		printf("%s begins: ", testName);

	if (hasPath(matrix, rows, cols, str) == expected)
		printf("Passed.\n");
	else
		printf("FAILED.\n");
}

//ABTG
//CFCS
//JDEH

//BFCE
void Test1()
{
    
    
	const char* matrix = "ABTGCFCSJDEH";
	const char* str = "BFCE";

	Test("Test1", (const char*)matrix, 3, 4, str, true);
}

//ABCE
//SFCS
//ADEE

//SEE
void Test2()
{
    
    
	const char* matrix = "ABCESFCSADEE";
	const char* str = "SEE";

	Test("Test2", (const char*)matrix, 3, 4, str, true);
}

int main()
{
    
    
	Test1();
	Test2();

	return 0;
}

Interview Question 13: The robot's range of motion
There is a square with m rows and n columns on the ground. A robot starts to move from the grid of coordinates (0,0). It can move one grid to the left, right, up, and down at a time, but it cannot enter the grid where the sum of the row and column coordinates is greater than k.
For example, when k is 18, the robot can enter the square (35,37) because 3+5 +3+7=18, but it cannot enter the square (35,38) because 3+5+3+8 =19.
How many grids can the robot reach?

int getDigitSum(int number)
{
    
    
    int sum = 0;
    while (number > 0)
    {
    
    
        sum += number % 10;
        number /= 10;
    }

    return sum;
}

int movingCountCore(int threshold, int rows, int cols, int row, int col, bool* visited)
{
    
    
    int count = 0;
    if (row >= 0 && row < rows && col >= 0 && col < cols
        && getDigitSum(row) + getDigitSum(col) <= threshold
        && !visited[row * cols + col])
    {
    
    
        visited[row * cols + col] = true;

        count = 1 + movingCountCore(threshold, rows, cols, row - 1, col, visited)
            + movingCountCore(threshold, rows, cols, row, col - 1, visited)
            + movingCountCore(threshold, rows, cols, row + 1, col, visited)
            + movingCountCore(threshold, rows, cols, row, col + 1, visited);
    }

    return count;
}

int movingCount(int threshold, int rows, int cols)
{
    
    
    if (threshold < 0 || rows <= 0 || cols <= 0)
        return 0;

    bool* visited = new bool[rows * cols];
    memset(visited, 0, rows * cols);

    int count = movingCountCore(threshold, rows, cols, 0, 0, visited);

    delete[] visited;

    return count;
}

int main()
{
    
    
    int step = movingCount(5, 10, 10);
    cout << step << endl;
    // 答案:21
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_46613023/article/details/114882744