一、题目描述
* 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,
* 每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。
* 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),
* 因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
二、解题思路
和上一题类似,用回溯法,打一个dp表记录是否满足条件。
三、java代码
public class Solution_67 {
/**
* 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,
* 每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。
* 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),
* 因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
*/
public int movingCount(int threshold,int rows,int cols){
boolean [] visted = new boolean[rows*cols];
for(boolean v:visted){
v = false;
}
int count = movingCountCore(threshold, rows, cols, 0, 0, visted);
return count;
}
public int movingCountCore(int threshold, int rows, int cols,int row,int col,boolean[] visted)
{
int count = 0;
if(check(threshold, rows, cols, row, col, visted)){
visted[row*cols+col] = true;
count = 1 + movingCountCore(threshold, rows, cols, row-1, col, visted)
+ movingCountCore(threshold, rows, cols, row, col-1, visted)
+ movingCountCore(threshold, rows, cols, row+1, col, visted)
+ movingCountCore(threshold, rows, cols, row, col+1, visted);
}
return count;
}
public boolean check(int threshold,int rows,int cols,int row,int col,boolean [] visted){
if(row>=0 && row<rows && col>=0 && col<cols
&& (getDigitSum(row)+getDigitSum(col)<=threshold)
&& !visted[row*cols+col]){
return true;
}
return false;
}
public int getDigitSum(int number) {
int sum = 0;
while(number > 0){
sum += number%10;
number /= 10;
}
return sum;
}
}
二刷代码:
class Solution {
public int movingCount(int m, int n, int k) {
boolean[][] visited = new boolean[m][n];
return move(visited, k, 0, 0);
}
public int move(boolean[][] visited, int k, int x, int y){
if(bitSum(x)+bitSum(y) > k){
return 0;
}
visited[x][y] = true;
int res = 1, m = visited.length-1, n = visited[0].length-1;
if(x-1 >= 0 && !visited[x-1][y]){ //上
res += move(visited, k, x-1, y);
}
if(x+1 <= m && !visited[x+1][y]){ //下
res += move(visited, k, x+1, y);
}
if(y-1 >= 0 && !visited[x][y-1]){ //左
res += move(visited, k, x, y-1);
}
if(y+1 <= n && !visited[x][y+1]){ //右
res += move(visited, k, x, y+1);
}
return res;
}
public int bitSum(int num){
if(num == 0) return 0;
int res = num % 10 ;
res += bitSum(num / 10);
return res;
}
}