1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { int ans = 0; Set<Integer> set = new HashSet<>(); public int movingCount(int m, int n, int k) { dfs(0, 0, m, n, k); return ans; }
public void dfs(int i, int j, int m, int n, int k) { if (judge(i, j, m, n, k)){ if (!set.contains(i * n + j)){ ans++; set.add(i * n + j); }else { return; } dfs(i + 1, j, m, n, k); dfs(i, j + 1, m, n, k); } }
public boolean judge(int i, int j, int m, int n, int k) { if (i < 0 || i >= m || j < 0 || j >= n) { return false; } if (getNum(i, j) > k) { return false; } return true; }
public int getNum(int m, int n) { int num = 0; while (m != 0) { num += m % 10; m = m / 10; }
while (n != 0) { num += n % 10; n = n / 10; } return num; } }
|