如题:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标
和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入
方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
这道题和第12题矩阵中的路径类似,都是在二维数组中移动,采用的方法也都是回溯法。机器人从地上的方格中移动,如果方格坐标数位之和超过阈值,则不能走动,否则可以走,方向包括上下左右四个方向。可以画个二维数组,从00点开始模拟走下试试。我们从00点出发,如果00点可走,则下一步有四个方向,分别是上下左右,调用递归四次,累加每个方向可以走动的个数。在每次走之前,需要检查坐标是否超出边界,该点是否可以走以及是否已经走过。因此,我们额外申请一个二维数组保存方格,初始化 的时候,对于每一个不能走的点置-1,对于已经走过的点置1,可走的点置0。流程比较简单,编码的时候别忘了非法参数的处理。
下面是本题c++编码:
class Solution {
public:
//获取数位之和
int getBitSum(int val)
{
int ret = 0;
while (val)
{
ret += val % 10;
val /= 10;
}
return ret;
}
//检查是否可走
int checkThreshold(int threshold, int row, int col)
{
int sum = getBitSum(row) + getBitSum(col);
return sum > threshold ? -1 : 0;
}
int movingCount(vector<vector<int>> &array, int row, int col, int prow,int pcol)
{
int cnt = 0;
//检查边界
if (prow < 0 || prow >= row || pcol < 0 || pcol >= col)
return 0;
//检查是否可走
if (array[prow][pcol] != 0)
return 0;
//可以走的话,置上标志位
cnt = array[prow][pcol] = 1;
//cout<<"["<<prow<<"]["<<pcol<<"]"<<endl;
//上、右、下、左
cnt += movingCount(array, row, col, prow-1, pcol) +
movingCount(array, row, col, prow, pcol+1) +
movingCount(array, row, col, prow+1, pcol) +
movingCount(array, row, col, prow, pcol-1);
return cnt;
}
int movingCount(int threshold, int rows, int cols)
{
vector<vector<int>> array(rows, vector<int>(cols, 0)), &rArray = array;
//特殊情况处理
if (threshold < 0 || (rows < 1 && cols < 1))
return 0;
//初始化方格
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = checkThreshold(threshold, i, j);
}
}
//返回可到达个数
return movingCount(rArray, rows, cols, 0, 0);
}
};
=============================================================================================
Linux应用程序、内核、驱动、后台开发交流讨论群(745510310),感兴趣的同学可以加群讨论、交流、资料查找等,前进的道路上,你不是一个人奥^_^。