剑指 Offer(第2版)面试题 13:机器人的运动范围
- 剑指 Offer(第2版)面试题 13:机器人的运动范围
- 解法1:深度优先搜索
剑指 Offer(第2版)面试题 13:机器人的运动范围
题目来源:24. 机器人的运动范围
解法1:深度优先搜索
我们从 (0, 0) 点开始,每次朝上下左右四个方向扩展新的节点即可。
扩展时需要注意新的节点需要满足如下条件:
- 之前没有遍历过,这个可以用一个 visited 数组来判断;
- 没有走出边界;
- 横纵坐标的各位数字之和小于 threshold。
最后答案就是所有遍历过的合法的节点个数 count。
代码:
class Solution
{
private:
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};
public:
int movingCount(int threshold, int rows, int cols)
{
// 特判
if (threshold < 0 || rows <= 0 || cols <= 0)
return 0;
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int count = dfs(threshold, rows, cols, 0, 0, visited);
return count;
}
// 辅函数 - 深度优先搜索
int dfs(int threshold, int rows, int cols, int row, int col, vector<vector<bool>> &visited)
{
if (row < 0 || row >= rows || col < 0 || col >= cols)
return 0;
int cnt = 0;
if (digitSum(row) + digitSum(col) <= threshold && visited[row][col] == false)
{
visited[row][col] = true;
cnt++;
for (int i = 0; i < 4; i++)
{
int x = row + dx[i], y = col + dy[i];
cnt += dfs(threshold, rows, cols, x, y, visited);
}
}
return cnt;
}
// 辅函数 - 求数 x 的数位之和
int digitSum(int x)
{
int digit_sum = 0;
while (x)
{
digit_sum += x % 10;
x /= 10;
}
return digit_sum;
}
};
复杂度分析:
时间复杂度:O(rows*cols)。每个节点最多只会入队一次,所以时间复杂度不会超过方格中的节点个数。最坏情况下会遍历方格中的所有点。
空间复杂度:O(rows*cols),用到了一个 visited 数组。