[Pregunta] P89 Sword se refiere a la oferta: Método de retroceso: Pregunta de entrevista 12: Ruta en la matriz (explicación detallada)

Pregunta de entrevista 12: Rutas en la matriz
Diseñe una función para determinar si existe una ruta que contenga todos los caracteres de una cadena en una matriz.
La ruta puede comenzar desde cualquier cuadrícula en la matriz, y cada paso puede mover una cuadrícula hacia la izquierda, derecha, arriba y abajo en la matriz. Si una ruta pasa a través de una cuadrícula de la matriz, la ruta no puede volver a ingresar a la cuadrícula.

Inserte la descripción de la imagen aquí

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

Pregunta de la entrevista 13: El rango de movimiento del robot
Hay un cuadrado con m filas yn columnas en el suelo. Un robot comienza a moverse desde la cuadrícula de coordenadas (0,0). Puede moverse una cuadrícula hacia la izquierda, derecha, arriba y abajo a la vez, pero no puede ingresar a la cuadrícula donde la suma de las coordenadas de fila y columna es mayor que k.
Por ejemplo, cuando k es 18, el robot puede ingresar al cuadrado (35,37) porque 3 + 5 + 3 + 7 = 18, pero no puede ingresar al cuadrado (35,38) porque 3 + 5 + 3 + 8 = 19.
¿Cuántas rejillas puede alcanzar el robot?

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

Supongo que te gusta

Origin blog.csdn.net/m0_46613023/article/details/114882744
Recomendado
Clasificación