Topics
Determine if a Sudoku is valid, according To:sudoku puzzles-the Rules.
The Sudoku board could be partially filled, where empty cells is 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.
Ideas:
First set three Boolean two-dimensional tag array: rowflags, Columnflags, Subflags, respectively, corresponding to the row, column, and child table.
Condition 1: There are only 1-9 numbers in Sudoku.
The next procedure is to update the three arrays, and the update process is as follows:
1. Cycle board, update in the process of the cycle. The outer loop variable is i
, the inner loop variable is j
.
2. Each inner loop calculates a subscript: because of k = border[i][j] - ‘1‘
condition 1, so border[i][j]
the corresponding character minus 1 of the ASCII code is exactly the number between 0-8.
3. For rows, if rowFlags[i][k]
true, indicates that a previous occurrence has occurred, so return false, otherwise rowFlags[i][k]
set to True.
4. For columns, if columnFlags[j][k]
true, indicates that a previous occurrence has occurred, so return false, otherwise columnFlags[j][k]
set to True.
5. For a child table, if subFlags[(i/3)*3 + j/3][k]
, (in this case, the row subscript is in the corresponding sub-box in that position), then the previous has occurred, so return false, otherwise subFlags[(i/3)*3 + j/3][k]
set to True.
Code:
Public Boolean Isvalidsudoku(Char[] board) {Final intSIZE =9;Boolean[] Rowflags =New Boolean[SIZE] [SIZE];Boolean[] Columnflags =New Boolean[SIZE] [SIZE];Boolean[] Subflags =New Boolean[SIZE] [SIZE]; for(inti =0; i < SIZE; i++) { for(intj =0; J < SIZE; J + +) {if(board[i][j]!='. ') {intK = Board[i][j]-' 1 ';if(Rowflags[i][k] | | columnflags[j][k] | | subflags[(i/3)*3+ j/3][K])return false; ROWFLAGS[I][K] = columnflags[j][k] = subflags[(i/3)*3+ j/3][K] =true; } } }return true;}
Result details (figure):
Leetcode 036 Valid Sudoku