题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
解题思路
- 设置一个和矩阵一般大小vector容器,初始值设置为0,机器人每访问一个矩阵格子,相应vector位置置1。
- 设置被调用函数,使用递归的方法,设置i 和 j, 依次遍历以i 和 j 为中心的上下左右4个位置,直到满足i 加 j 的数位等于给定值为止。
- 设置被调用函数,求一个数的位数和。
代码实现
class Solution {
public:
int countvalue(int num)
{
int value = 0;
while(num > 0)
{
value += num % 10;
num /= 10;
}
return value;
}
int moving(int threshold, vector<int>& ivec, int i, int j, int rows, int cols)
{
int count = 0;
if(i >= 0 and i < rows and j >= 0 and j < cols and countvalue(i) + countvalue(j) <= threshold and ivec[i * cols + j] == 0)
{
ivec[i * cols + j] = 1;
count = 1 +
moving(threshold, ivec, i + 1, j, rows, cols) +
moving(threshold, ivec, i - 1, j, rows, cols) +
moving(threshold, ivec, i, j + 1, rows, cols) +
moving(threshold, ivec, i, j - 1, rows, cols);
}
return count;
}
int movingCount(int threshold, int rows, int cols)
{
vector<int> ivec(rows * cols, 0);
return moving(threshold, ivec, 0, 0, rows, cols);
}
};