The meaning of problems
Please design a function that determines whether there is a route that contains all the characters of a character string in a matrix. A lattice path may start from any of the matrix, each step in the matrix can be left, right, up, down one grid. If a route that passes through a matrix of a grid, the path can not enter the lattice. E.g
For example
the matrix containing the path "bcced" in a string, but does not contain the matrix "abcb" path, as a character string in the first row of the matrix b occupy the first second after the lattice, can not re-enter the path this grid.
Thinking
class Solution {
public:
bool core(char *matrix, int row, int col, int rows, int cols, char *str, bool **visit) {
//这是个递归调用,传入到最后了,说明整个字符串检测完了,返回true
if (*str == 0)
return true;
//如果当前要访问的格子超过边界,或者不相等,或者已经被访问过了,都要返回false
if (row >= rows || col >= cols || row < 0 || col < 0 || matrix[col + row * cols] != *str || visit[row][col])
return false;
bool has_path = false;
//假设当前格子被访问
visit[row][col] = 1;
//递归的思想,从当前格子出发,上下左右是否有路径
has_path = core(matrix, row + 1, col, rows, cols, str + 1, visit) ||
core(matrix, row, col + 1, rows, cols, str + 1, visit) ||
core(matrix, row - 1, col, rows, cols, str + 1, visit) ||
core(matrix, row, col - 1, rows, cols, str + 1, visit);
//如果没有路径,就回退,然后这个格子变成没访问过的
if (!has_path)
visit[row][col] = 0;
//返回
return has_path;
}
bool hasPath(char *matrix, int rows, int cols, char *str) {
//设计一个visit数组,用来标记已经访问过的单元
bool **visit = new bool *[rows];
for (int i = 0; i < rows; i++)
visit[i] = new bool[cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
visit[i][j] = 0;
//从任意单元格开始检测是否存在指定字符串
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
if (core(matrix, i, j, rows, cols, str, visit))
return true;
}
return false;
}
};