zerofly's Blog

努力不一定成功,但不努力一定不会成功

0%

机器人的运动范围


题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

解题思路

这道题,也是使用回溯算法,与上一题的区别就是:

  • 给定了起始的坐标;

不同之处:

  • 判断条件不同了:行坐标与列坐标之 “和” 不大于 k。(这就涉及整数的拆分)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution
{
public:
int movingCount (int threshold, int rows, int cols)
{
if (threshold < 1 || rows < 1 || cols < 1)
return 0;

bool* visit = new bool[rows * cols];
memset(visit, 0, rows * cols);

int result = movingCountCore (threshold, rows, cols, 0, 0, visit);
delete[] visit;
return result;
}
private:
int movingCountCore (int threshold, int rows, int cols, int row, int col, bool* visit)
{
int count = 0;
if (row >= 0 && row < rows && col >= 0 && col < cols && getSum(row) + getSum(col) <= threshold && !visit[row * cols + col])
{
visit[row * cols + col] = true;
count = 1 + movingCountCore (threshold, rows, cols, row - 1, col, visit) +
movingCountCore (threshold, rows, cols, row + 1, col, visit) +
movingCountCore (threshold, rows, cols, row, col - 1, visit) +
movingCountCore (threshold, rows, cols, row, col + 1, visit);
}
return count;
}
int getSum (int num)
{
int sum = 0;
while (num)
{
sum += num%10;
num /= 10;
}
return sum;
}
};

参考博文链接:https://cuijiahua.com/blog/2018/02/basis_66.html

文章作者:zerofly

发布时间:2020年06月09日 - 18:06

原始链接:http://zeroflycui.github.io/6f7abd.html

许可协议: 转载请保留原文链接及作者。