classSolution{ publicintmovingCount(int m, int n, int k){ //广度优先搜索 Queue<int[]> queue = new LinkedList<>(); Set<String> used = new HashSet<>(); used.add("0,0"); queue.add(newint[] {0, 0}); int[][] foots = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} }; int count = 0;
while (!queue.isEmpty()) { int[] num = queue.poll(); int mK = getK(num[0], num[1]); if (mK > k) { continue; }
for (int[] foot : foots) { int x = foot[0] + num[0]; int y = foot[1] + num[1]; if (x < 0 || y < 0 || x >= m || y >= n) { continue; } String key = x + "," + y; if (used.contains(key)) { continue; } used.add(key);
privateintgetK(int i, int j){ int sum = 0; while (i > 0) { int n = i % 10; sum += n; i /= 10; } while (j > 0) { int n = j % 10; sum += n; j /= 10; } return sum; }