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

本文介绍两个算法问题:一是判断字符串是否能在给定的矩阵中找到路径;二是统计矩阵中满足特定条件的格子数量。通过递归和辅助数组实现深度优先搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/bloomingFlower/p/7804329.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值