タイトル説明
接地グリッドと、m行n列。グリッドからロボットが移動、右、左だけ毎回0,0座標上下四方セルが、グリッドの行および列の座標を入力することができないビットkの数の合計よりも大きいです。kが18である場合、例えば、ロボットが3 + 3 + 5 + 7 = 18から、ボックス(35、37)を入力することができます。3 + 3 + 5 + 8 = 19しかし、それは、ボックス(35、38)を入力することができません。ロボットは、格子の数に到達することができるだろうか?
アイデア解析
同時に満たすために、グリッドにマーク配列アクセス、ロボットの条件を設定し、同じ考えの最後のタイトル、:バックトラック:
- このグリッドはマークされていません
- グリッドとビットインデックスの和<=閾値は、
垂直および水平グリッドを入力することができるかどうかを決定するために継続します
Javaコード
public class Offer13 {
public static void main(String[] args) {
}
public static int movingCount(int threshold, int rows, int cols)
{
return Solution1(threshold, rows, cols);
}
/**
*
* 思路:设置一个访问标记数组,机器人进入格子的条件要同时满足
* 1.这个格子没有被标记
* 2.这个格子的下标位数之和 <= threshold
* 继续判断其上下左右的格子是否可以进入
* @param threshold
* @param rows
* @param cols
* @return
*/
private static int Solution1(int threshold, int rows, int cols)
{
if(threshold < 0 || rows < 0 || cols < 0) {
return 0;
}
boolean[] visited = new boolean[rows*cols];
for(boolean b: visited) {
b = false;
}
int count = movingCountCore(threshold,rows,cols,0,0,visited);
return count;
}
private static int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] visited) {
if(row < 0 || row >= rows || col <0 || col>=cols
|| getDigitSum(row)+getDigitSum(col) > threshold
|| visited[row*cols+col]) { // 判断是否可以进入此格子
return 0;
}
int count = 0;
visited[row*cols+col] = true;
count = 1 + movingCountCore(threshold, rows, cols, row, col-1, visited)
+ movingCountCore(threshold, rows, cols, row, col+1, visited)
+ movingCountCore(threshold, rows, cols, row-1, col, visited)
+ movingCountCore(threshold, rows, cols, row+1, col, visited);
return count;
}
private static int getDigitSum(int number) {
int sum = 0;
while(number > 0) {
sum += number%10;
number /= 10;
}
return sum;
}
}