Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91384780
welcome to my blog
Offer surface prove safety questions 13 (java version): the movement range of the robot
Title Description
A ground grid and m rows n columns. A robot moves from the grid coordinates 0,0, every time only left, right, upper, lower four directions a cell, but can not enter the row and column coordinates of the grid is greater than the sum of the number of bits k. For example, when k is 18, the robot can enter the box (35, 37), because 3 + 3 + 5 + 7 = 18. However, it can not enter the box (35, 38), because 3 + 3 + 5 + 8 = 19. Will the robot be able to reach the number of lattice?
Thinking
- Recursive understood: recursive function, the first argument indicates the processing status of the current, then a recursive call to the function (s) a state
the complexity
- time complexity
- Space complexity: create boolean [], it is O (n)
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
boolean[] flag = new boolean[rows*cols];
for(int i=0 ; i<rows*cols; i++)
flag[i]=false;
int result = movingCountCore(threshold, rows, cols, 0, 0, flag);
return result;
}
private int movingCountCore(int threshold, int rows, int cols, int i, int j, boolean[] flag){
// 从(i,j)开始,能否向上下左右移动? 可以同时探索多个方向
// 走过的地方就不能再走了, 注意标识一下flag
// 判断(i,j)是否越界, (i,j)能否到达, (i,j)数位和是否大于threshold
int index = i*cols+j;
if(i<0 || i>= rows || j<0 || j>=cols || flag[index]==true || sumLargerThanK(i, j, threshold))
return 0;
// 执行到这里说明(i,j)可以到达, 对应的flag置true, 表示不能再到达(i,j)
flag[index] = true;
// 计数加一, 之后继续递归探索(i,j)上下左右的点
int count = 0;
count = 1 + movingCountCore(threshold, rows, cols, i+1, j, flag) +
movingCountCore(threshold, rows, cols, i-1, j, flag) +
movingCountCore(threshold, rows, cols, i, j+1, flag) +
movingCountCore(threshold, rows, cols, i, j-1, flag);
return count;
}
private boolean sumLargerThanK(int i, int j, int threshold){
return getSum(i)+getSum(j) > threshold;
}
private int getSum(int i){
int sum=0;
while(i>0){
sum += i%10;
i /= 10;
}
return sum;
}
}