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
| class Solution { public boolean checkValidGrid(int[][] grid) { if (grid[0][0] != 0) return false; this.grid = grid; n = grid.length; return dfs(0, 0, 0); }
private boolean dfs(int i, int j, int step) { if (step == n * n - 1) return grid[i][j] == n * n - 1; for (int[] dir : dirs) { int row = i + dir[0], col = j + dir[1]; if (isValid(row, col) && grid[row][col] == step + 1 && dfs(row, col, step + 1)) return true; } return false; }
private boolean isValid(int row, int col) { return row >= 0 && col >= 0 && row < n && col < n; }
int[][] grid, dirs = new int[][]{{-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {-2, 1}, {-1, 2}, {2, 1}, {1, 2}}; int n; }
|