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.
Solution:
对于每一行,每一列,每个九宫格进行验证,总共需要27次验证,每次看九个元素。
时间复杂度就是O(3*n^2), n=9。public class Solution { public boolean isValidSudoku(char[][] board) { if(board == null || board.length != 9 || board[0].length != 9) return false; for(int i = 0; i < 9; i++) { //check each row HashSetmap = new HashSet (); for(int j = 0; j < 9; j++) { if(!map.add(board[i][j]) && board[i][j] != '.') { return false; } } } for(int i = 0; i < 9; i++) { //check each column HashSet map = new HashSet (); for(int j = 0; j < 9; j++) { if(!map.add(board[j][i]) && board[j][i] != '.') { return false; } } } for(int i = 0; i < 3; i++) { //check each 9 sub-boxes for(int j = 0; j < 3; j++) { HashSet map = new HashSet (); for(int m = i * 3; m < i * 3 + 3; m++) { for(int n = j * 3; n < j * 3 + 3; n++) { if(!map.add(board[m][n]) && board[m][n] != '.') { return false; } } } } } return true; } }
No comments:
Post a Comment