Prove safety Offer: range of motion of the robot (java version)

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?

analysis

In Flag construct an auxiliary array [] [], you can be reached if the current position, it will correspond to the position marked 1, showing been reached, to avoid double counting.
The number of the (0,0) starts, if can reach, the reach of (1 + vertical and horizontal directions) may reach the number.

public class Solution {
    public int movingCount(int threshold, int rows, int cols){
        byte[][] flag = new byte[rows][cols];
        return count( threshold, 0, 0, rows, cols, flag);
    }
    private int count(int k, int R, int C, int rows, int cols, byte[][] flag){
        if(R > rows-1 || R<0 || C>cols-1 || C<0 || numberSum(R,C)>k || flag[R][C]==1)
            return 0;
        flag[R][C] = 1;
        return 1 + count(k, R-1, C, rows, cols, flag) +
                   count(k, R+1, C, rows, cols, flag) +
                   count(k, R, C-1, rows, cols, flag) +
                   count(k, R, C+1, rows, cols, flag);
    }
    private int numberSum(int R,int C){
        int sum1 = 0;
        int sum2 = 0;
        while(R>0){
            sum1 += (R%10);
            R /= 10;
        }
        while(C>0){
            sum2 += (C%10);
            C /= 10;
        }
        return sum1 + sum2;
    }
}

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/90717700