There is a square of m rows and n columns on the ground. A robot moves from a grid of coordinates 0,0. Each time, it can only move one grid in four directions: left, right, up and down, but it can't enter a grid whose digit sum of row coordinates and column coordinates is larger than k. For example, when k is 18, the robot can enter the grid (35,37), because 3+5+3+7 = 18. However, it cannot enter the grid (35,38), because 3+5+3+8 = 19. How many grids can the robot reach?
class SolutionMethod1{ public int movingCount(int threshold,int rows,int cols){//threshold constraints, rows grid rows, cols grid columns, boolean[] visted = new boolean[rows*cols]; for(int i = 0; i < visted.length; i++) visted[i] = false; int count = movingCountCore(threshold,rows,cols,0,0,visted); return count; //Maximum number of travable squares } public int movingCountCore(int threshold,int rows,int cols,int row,int col,boolean[] visted){ //threshold; rows grid rows; cols grid rows; row number currently processed by row; column number currently processed by col; visted access tag array 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; //Maximum number of travable squares } 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){ //Number number int sum = 0; while(number > 0){ sum += number%10; number /= 10; } return sum; //The sum of digits of a number } } public class Solution { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); System.out.println("Please enter restrictions k:"); int k = scanner.nextInt(); System.out.println("Please enter the number of rows in the grid. m: "); int m = scanner.nextInt(); System.out.println("Please enter the number of columns in the grid. n:"); int n = scanner.nextInt(); SolutionMethod1 solution1 = new SolutionMethod1(); scanner.close(); System.out.println("The number of squares that a matrix can reach is:"); System.out.println(solution1.movingCount(k, m, n)); } }