boolcheckValidGrid(int** grid, int gridSize, int* gridColSize) { if (grid[0][0] != 0) { returnfalse; } int n = gridSize; int indices[n * n][2]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { indices[grid[i][j]][0] = i; indices[grid[i][j]][1] = j; } } for (int i = 1; i < n * n; i++) { int dx = abs(indices[i][0] - indices[i - 1][0]); int dy = abs(indices[i][1] - indices[i - 1][1]); if (dx * dy != 2) { returnfalse; } } returntrue; }
publicclassSolution { publicboolCheckValidGrid(int[][] grid) { if (grid[0][0] != 0) { returnfalse; } int n = grid.Length; int[][] indices = newint[n * n][]; for (int i = 0; i < n * n; i++) { indices[i] = newint[2]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { indices[grid[i][j]][0] = i; indices[grid[i][j]][1] = j; } } for (int i = 1; i < n * n; i++) { int dx = Math.Abs(indices[i][0] - indices[i - 1][0]); int dy = Math.Abs(indices[i][1] - indices[i - 1][1]); if (dx * dy != 2) { returnfalse; } } returntrue; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defcheckValidGrid(self, grid: List[List[int]]) -> bool: if grid[0][0] != 0: returnFalse n = len(grid) indices = [[] for _ inrange(n * n)] for i inrange(n): for j inrange(n): indices[grid[i][j]] = [i, j] for i inrange(1, n * n, 1): dx = abs(indices[i][0] - indices[i - 1][0]) dy = abs(indices[i][1] - indices[i - 1][1]) if dx * dy != 2: returnFalse returnTrue