原题链接在这里:https://leetcode.com/problems/valid-sudoku/
题目:
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
Example 1:
Input: [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] Output: true
Example 2:
Input: [ ["8","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] Output: false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentioned rules.
- The given board contain only digits
1-9
and the character'.'
. - The given board size is always
9x9
.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
题解:
先一行一行检查,再一列一列检查,这里注意外层for loop是j
最后一个一个小方块来检查, for each box, have a count k within [0,8], have (i + k/3, j + k%3) as coordinate.
Time Complexity: O(n^2). n = board.length. Space: O(1).
AC Java:
1 class Solution { 2 public boolean isValidSudoku(char[][] board) { 3 if(board == null || board.length != 9 || board[0].length != 9){ 4 return false; 5 } 6 7 for(int i = 0; i<9; i++){ 8 HashSet<Character> hs = new HashSet<>(); 9 for(int j = 0; j<9; j++){ 10 if(board[i][j] != '.'){ 11 if(!Character.isDigit(board[i][j]) || !hs.add(board[i][j])){ 12 return false; 13 } 14 } 15 } 16 } 17 18 for(int j = 0; j<9; j++){ 19 HashSet<Character> hs = new HashSet<>(); 20 for(int i = 0; i<9; i++){ 21 if(board[i][j] != '.'){ 22 if(!Character.isDigit(board[i][j]) || !hs.add(board[i][j])){ 23 return false; 24 } 25 } 26 } 27 } 28 29 for(int i = 0; i<9; i+=3){ 30 for(int j = 0; j<9; j+=3){ 31 HashSet<Character> hs = new HashSet<>(); 32 for(int k = 0; k<9; k++){ 33 if(board[i + k/3][j + k%3] != '.'){ 34 if(!hs.add(board[i + k/3][j + k%3])){ 35 return false; 36 } 37 } 38 } 39 } 40 } 41 42 return true; 43 } 44 }