Valid Sudoku
Search a 2D matrix can be prerequisite for this problem. Use mid/n to get row index, use mid%n to get column index.
Maybe Spiral Matrix can use the same technique.
Solution 1:
Row, column and cube can be checked in one loop. When checking ith row, by swaping i and j, can check ith column. Need to memorize the cube index calculation.
Divide the board into 9 3x3. The rowIndex and colIndex are starting indexes of each 3x3. With this information is very easy to iterate through the 3x3 with j incrementing.
Solution 2:
Check row, col and cube one by one. It's easier to come up with the cube's indexes. But with much larger time complexity.
Check the solution of Sudoku Solver.
Maybe Spiral Matrix can use the same technique.
Solution 1:
Row, column and cube can be checked in one loop. When checking ith row, by swaping i and j, can check ith column. Need to memorize the cube index calculation.
Divide the board into 9 3x3. The rowIndex and colIndex are starting indexes of each 3x3. With this information is very easy to iterate through the 3x3 with j incrementing.
class Solution { public boolean isValidSudoku(char[][] board) { if (board == null || board[0].length == 0) return false; for (int i = 0; i < board.length; i++) { Set<Character> rowSet = new HashSet<>(); Set<Character> colSet = new HashSet<>(); Set<Character> cubeSet = new HashSet<>(); for (int j = 0; j < board[0].length; j++) { // check row if (board[i][j] != '.' && !rowSet.add(board[i][j])) return false; if (board[j][i] != '.' && !colSet.add(board[j][i])) return false; int rowIndex = 3 * (i / 3); int colIndex = 3 * (i % 3) ; if (board[rowIndex + j / 3][colIndex + j % 3] != '.'
&& !cubeSet.add(board[rowIndex + j / 3][colIndex + j % 3])) return false;
}
}
return true;
}
}
Solution 2:
Check row, col and cube one by one. It's easier to come up with the cube's indexes. But with much larger time complexity.
Check the solution of Sudoku Solver.
评论
发表评论