36. Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
分析 : 3 个hashset
public class Solution { public boolean isValidSudoku(char[][] board) { for(int i = 0 ; i < 9 ; i++){ HashSet<Character> row = new HashSet<>(); HashSet<Character> col = new HashSet<>(); HashSet<Character> cub = new HashSet<>(); for(int j = 0 ; j < 9 ; j++){ if(board[i][j] != '.' && !row.add(board[i][j])) return false; if(board[j][i] != '.' && !col.add(board[j][i])) return false; int rowCub = 3 * (i / 3); int colCub = 3 * (i % 3); if(board[rowCub + j/3][colCub + j %3] != '.' && !cub.add(board[rowCub + j/3][colCub + j %3] )) return false; } } return true; } }