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
| class Solution { private static final int[][] DIRECTIONS = new int[][]{{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};
public boolean checkValidGrid(int[][] grid) { return dfs(grid, 0, 0, 0); }
private boolean dfs(int[][] grid, int i, int j, int excepted) { int m = grid.length, n = grid[0].length;
if (grid[i][j] != excepted) { return false; }
if (excepted == m * n - 1) { return true; }
for (int[] direction : DIRECTIONS) { int nextI = i + direction[0], nextJ = j + direction[1]; if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n) { if (dfs(grid, nextI, nextJ, excepted + 1)) { return true; } } }
return false; } }
|