publicintmovingCount(int m, int n, int k){ boolean[][] vis = newboolean[m][n]; return solve(0, 0, m, n, vis, k); }
privateintsolve(int x, int y, int m, int n, boolean[][] vis, int k){ if (x >= m || y >= n || vis[x][y] || (getPlaces(x) + getPlaces(y)) > k) { return0; } vis[x][y] = true; // 先在横向上一直深度遍历 return1 + solve(x + 1, y, m, n, vis, k) + solve(x, y + 1, m, n, vis, k);
} } publicstaticintgetPlaces(int num){ int s = 0; while (num != 0) { s += num % 10; num = num / 10; } return s; }
publicstaticintgetPlaces(int num){ int s = 0; while (num != 0) { s += num % 10; num = num / 10; } return s; }
privatestaticclassSolution2{ publicintmovingCount(int m, int n, int k){ int res = 0; boolean[][] vis = newboolean[m][n]; Queue<int[]> queue = new LinkedList<>(); queue.add(newint[]{0, 0}); while (!queue.isEmpty()) { int[] poll = queue.poll(); assert poll != null; int x = poll[0]; int y = poll[1]; if (x >= m || y >= n || vis[x][y] || (getPlaces(poll[0]) + getPlaces(poll[1])) > k) { continue; } res++; vis[x][y] = true; queue.add(newint[]{x + 1, y}); queue.add(newint[]{x, y + 1});