地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,它每次可以向左、右、上、下移动一个,但不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入放个(35,37),因为3+5+3+7=18。但它不能进入(35,38),因为3+5+3+8=19。请问该机器人能够到达多少个格子?
思路:跟之前《矩阵中的路径》那题相似的背景。抽象化X,Y轴,可以拿一维或者二维数组表示,一维数组的话就要传入行列数。因为要试探下一步能不能走,即符不符合条件。套路也有了,一个方法作为入口方法,一个方法作为核心方法,一个方法作为条件方法。
入口方法:
static int MovingCount(int threshold, int rows, int cols)
{
if (threshold<0||rows<=0||cols<=0)
{
return 0;
}
bool[] visited = new bool[rows * cols];
for (int i = 0; i < rows*cols; i++)
{
visited[i] = false;
}
int count = MovingCountCore(threshold, rows, cols,
0, 0, visited);
return count;
}
输入参数有阈值k,行列数则代表矩形大小,理论上矩阵的行或列数位之和不应小于阈值k。入口方法开局应对输入参数做有效性判断,提高代码的鲁棒性。然后矩阵对应一个bool数组,开局全为false。然后开始核心方法,从(0,0)点开始计算。
static 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))
{
visited[row * cols + col] = true;
count = 1 + MovingCountCore(threshold, rows, cols,
row - 1, col, visited)
+ MovingCountCore(threshold, rows, cols,
row, col - 1, visited)
+ MovingCountCore(threshold, rows, cols,
row + 1, col, visited)
+ MovingCountCore(threshold, rows, cols,
row, col + 1, visited);
}
return count;
}
核心方法是回溯的核心,感觉很有栈的思想。
static bool check(int threshold, int rows, int cols, int row, int col, bool[] visited)
{
if (row>=0&&row<rows&&col>=0&&col<cols
&&getDigitSum(row)+getDigitSum(col)<=threshold
&&!visited[row*cols+col])
{
return true;
}
return false;
}
static int getDigitSum(int number)
{
int sum = 0;
while (number>0)
{
sum += number % 10;
number /= 10;
}
return sum;
}
最后就是两个逻辑判断方法。
心得:入口方法、回溯核心方法,依据判断方法,这三个方法的套路似乎对这种题型很有用!