失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 剑指offer 回溯法 面试题12 矩阵中的路径 面试题13 机器人的运动范围

剑指offer 回溯法 面试题12 矩阵中的路径 面试题13 机器人的运动范围

时间:2021-01-05 12:31:14

相关推荐

剑指offer 回溯法 面试题12 矩阵中的路径 面试题13 机器人的运动范围

题目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 机器人的运动范围》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。