题目12
bool has_path_core(char *matrix, int rows, int cols, int row, int col, string a, int &pathlen, bool *visited){
if(pathlen == a.length() - 1)
return true;
bool result = false;
if(row >= 0 && col >= 0 && row < rows && col < cols && matrix[row * cols + col] == a[pathlen] && !visited[row * cols + col]) {
++pathlen;
visited[row * cols + col] = true;
result = has_path_core(matrix, rows, cols, row - 1, col, a, pathlen, visited) ||
has_path_core(matrix, rows, cols, row + 1, col, a, pathlen, visited) ||
has_path_core(matrix, rows, cols, row, col + 1, a, pathlen, visited) ||
has_path_core(matrix, rows, cols, row, col - 1, a, pathlen, visited);
if(!result) {
--pathlen;
visited[row * cols + col] = false;
}
}
return result;
}
题目13
int get_digit(int num) {
int result = 0;
while(num > 0) {
result += num % 10;
num /= 10;
}
return result;
}
int nums(int threshold, int rows, int cols, int row, int col, int &result, bool *help) {
if(!help[row * cols + col] && row < rows && row >= 0 && col >= 0 && col < cols
&& (get_digit(row) + get_digit(col)) <= threshold) {
++result;
help[col + row * cols] = true;
nums(threshold, rows, cols, row - 1, col, result, help);
nums(threshold, rows, cols, row + 1, col, result, help);
nums(threshold, rows, cols, row, col - 1, result, help);
nums(threshold, rows, cols, row, col + 1, result, help);
}
return result;
}
如果觉得《剑指offer 回溯法 面试题12 矩阵中的路径 面试题13 机器人的运动范围》对你有帮助,请点赞、收藏,并留下你的观点哦!