【刷题】P89剑指offer:回溯法:面试题12:矩阵中的路径(详解)

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

在这里插入图片描述

#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;
}

面试题13:机器人的运动范围
地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和大于k的格子。
例如,当k为18时,机器人能够进入方格(35,37),因为3+5 +3+7=18,但它不能进入方格(35,38),因为3+5+3+8=19。
请问该机器人能够到达多少个格子?

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;
}

猜你喜欢

转载自blog.csdn.net/m0_46613023/article/details/114882744