题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
考察点:回溯法,递归使用;二维矩阵当数组处理。
方法1:回溯。
思路如代码:
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
if (threshold < 0 || rows <= 0 || cols <= 0)
return 0;
bool* visited = new bool[rows * cols];//声明访问数组
memset(visited, false, rows * cols); //访问数组初始化
int count = movingCountCore(threshold,rows,cols,0,0,visited); //计算特定阈值下,特定行列数下可到达的最大块数
delete[] visited;//释放数组空间
return count;
}
int movingCountCore(int threshold, int rows, int cols, int row, int col, bool* visited)//
{
int count = 0;
if (check(threshold, rows, cols, row, col, visited))//检测函数,判断是否进入坐标为(row,col)方格
{
visited[row * cols + col] = true;
count = 1 + //用深度优先遍历,本方格的1+向右走和向下走的计数和
movingCountCore(threshold, rows, cols, row + 1, col, visited) +
movingCountCore(threshold, rows, cols, row, col + 1, visited);
}
return count;
}
bool check(int threshold, int rows, int cols, int row, int col, bool* visited)
{
if (row >= 0 && row < rows && col >= 0 && col < cols && getDitSum(row) + getDitSum(col) <= threshold && !visited[row * cols + col])
{
return true;
}
return false;
}
int getDitSum(int number)//得到位数之和
{
int sum = 0;
while (number > 0)
{
sum += number % 10;
number /= 10;
}
return sum;
}
};
方法2:动态规划(待解决)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)