题目描述:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路一:回溯法
1、从(0,0)开始走,每成功走一步标记当前位置为1,然后从当前位置往四个方向探索, 返回4 + 1 个方向的探索值之和。
2、探索时,判断当前节点是否可达的标准为:
1)当前节点在矩阵内;
2)当前节点未被访问过;
3)当前节点满足limit限制。
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
int[][] flag = new int[rows][cols];
return helper(0, 0, rows, cols, flag, threshold);
}
private int helper(int i, int j, int rows, int cols, int[][] flag, int threshold)
{
if (i < 0 || i >= rows || j < 0 || j >= cols || numSum(i) + numSum(j) > threshold || flag[i][j] == 1)
return 0;
flag[i][j] = 1;
return helper(i - 1, j, rows, cols, flag, threshold)
+ helper(i + 1, j, rows, cols, flag, threshold)
+ helper(i, j - 1, rows, cols, flag, threshold)
+ helper(i, j + 1, rows, cols, flag, threshold)
+ 1;
}
private int numSum(int i)
{
int sum = 0;
do {
sum += i % 10;
}while ((i = i / 10) > 0);
return sum;
}
}
思路二:
动态规划
dp[i][j]表示是否可以到达,统计数字中true的个数,即为可以到达的格子数
1、首先需要初始化第一行和第一列,这时候只考虑前一个或者上一个是否能到达,如果坐标也满足就可以达到
2、考虑其他的点,只需要关注左边和上面的点,如果左边或上面的点可以达到,而且(i,j)的坐标满足数位之和小于threshold,那么dp[i][j]为true
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
if (threshold < 0)
return 0;
boolean[][] dp = new boolean[rows][cols];
dp[0][0] = true;
for (int i = 1 ; i < rows; i++)
{
if (dp[i - 1][0] == true && canReach(threshold, i, 0))
dp[i][0] = true;
else
dp[i][0] = false;
}
for (int j = 1; j < cols; j++)
{
if (dp[0][j - 1] == true && canReach(threshold, 0, j))
dp[0][j] = true;
else
dp[0][j] = false;
}
for (int i = 1; i < rows; i++)
{
for (int j = 1; j < cols; j++)
{
if ((dp[i - 1][j] == true && canReach(threshold, i, j)) || (dp[i][j - 1] == true && canReach(threshold, i, j)))
dp[i][j] = true;
else
dp[i][j] = false;
}
}
int count = 0;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (dp[i][j])
count++;
return count;
}
private boolean canReach(int threshold, int i, int j)
{
int sum = 0;
while (i > 0)
{
sum += i % 10;
i /= 10;
}
while (j > 0)
{
sum += j % 10;
j /= 10;
}
return sum <= threshold;
}
}