地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
示例 1:
输入:m = 2, n = 3, k = 1
输出:3
示例 2:
输入:m = 3, n = 1, k = 0
输出:1
public class Solution { public static void main(String[] args) { Solution solution = new Solution(); int i = solution.movingCount(2, 3, 1); System.out.println(i); } private int Count = 0; private boolean[][] visited = null; public int movingCount(int m, int n, int k) { visited = new boolean[m][n]; move(0,0,m,n,k); return Count; } private void move(int i, int j, int m, int n, int k) { Count++; int upi = (i-1)>=0?(i-1):i; int dni = (i+1)>=m?i:(i+1); int ltj = (j-1)>=0?(j-1):j; int rtj = (j+1)>=n?j:(j+1); visited[i][j] = true; if (!visited[upi][j] && nums(upi,j) <=k){ move(upi,j,m,n,k); } if (!visited[dni][j] && nums(dni,j) <=k){ move(dni,j,m,n,k); } if (!visited[i][ltj] && nums(i,ltj) <=k){ move(i,ltj,m,n,k); } if (!visited[i][rtj] && nums(i,rtj) <=k){ move(i,rtj,m,n,k); } } private int nums(int i, int j) { int Count = 0; while (i>0){ Count +=i%10; i=i/10; } while (j>0){ Count +=j%10; j=j/10; } return Count; } }