题目:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
解答:
1 public class Solution { 2 3 public static void main(String[] args) { 4 int threshold = 10; 5 int rows = 3; 6 int cols = 7; 7 8 System.out.println(movingCount(threshold, rows cols)); 9 } 10 11 public static int movingCount(int threshold, int rows, int cols) 12 { 13 if(threshold < 0 || rows <= 0 || cols <= 0) { 14 return 0; 15 } 16 17 boolean[] visited = new boolean[rows*cols]; 18 for(int i = 0; i < rows*cols; i++) { 19 visited[i] = false; 20 } 21 22 int count = movingCount(threshold, rows, cols, 0, 0, visited); 23 24 return count; 25 } 26 27 public static int movingCount(int threshold, int rows, int cols, int row, int col, boolean[] visited){ 28 int count = 0; 29 30 if(check(threshold, rows, cols, row, col, visited)) { 31 32 visited[row*cols+col] = true; 33 34 count = 1 + movingCount(threshold, rows, cols, row+1, col, visited)+ 35 movingCount(threshold, rows, cols, row-1, col, visited)+ 36 movingCount(threshold, rows, cols, row, col+1, visited)+ 37 movingCount(threshold, rows, cols, row+1, col-1, visited); 38 } 39 40 return count; 41 } 42 43 44 public static boolean check(int threshold, int rows, int cols, int row, int col, boolean[] visited) { 45 if(row >=0 && row < rows && col >= 0 && col < cols && getDigitSum(row)+getDigitSum(col) <= threshold && !visited[row*cols+col]){ 46 return true; 47 } else { 48 return false; 49 } 50 } 51 52 53 public static int getDigitSum(int num) { 54 55 int sum = 0; 56 while(num > 0) { 57 sum = sum + num % 10; 58 num = num /10; 59 } 60 61 return sum; 62 } 63 }