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.
Subscribe to see which companies asked this question
Solution 1: Judging each row, each column, each 3x3 block has the same number, time complexity O (n^2), Spatial complexity O (n).
classSolution { Public: BOOLIsvalidsudoku (vector<vector<Char>>&Board) { if(Board.empty () | | board[0].empty ())return false; intn =board.size (); Vector<int> Row (9,0); Vector<int> col (9,0); for(inti =0; I < n; ++i) {row.assign (9,0); Col.assign (9,0); for(intj =0; J < N; ++j) {if(Board[i][j]! ='.') { if(Row[board[i][j]-'1'] ==1)return false; Else++ROW[BOARD[I][J]-'1']; } if(Board[j][i]! ='.') { if(Col[board[j][i]-'1'] ==1)return false; Else++col[board[j][i]-'1']; }}} vector<int> C3 (9,0); for(intK =0; K < n * N/9; ++k) {c3.assign (9,0); intStarti = k/3*3, STARTJ = k%3*3; for(intcol = Starti; Col < Starti +3; ++Col) { for(introw = STARTJ; Row < STARTJ +3; ++row) { if(Board[col][row]! ='.') { if(C3[board[col][row]-'1'] ==1)return false; Else++c3[board[col][row]-'1']; } } } } return true; }};
When the spatial complexity is O (n^2), it can be solved with a two-layer loop:
classSolution { Public: BOOLIsvalidsudoku (vector<vector<Char>>&Board) { if(Board.empty () | | board[0].empty ())return false; intn =board.size (); Vector<int> Row (9,0); Vector<int> col (9,0); Vector< vector<int> > Cub (9, vector<int> (9,0)); for(inti =0; I < n; ++i) {row.assign (9,0); Col.assign (9,0); for(intj =0; J < N; ++j) {if(Board[i][j]! ='.') { if(Row[board[i][j]-'1'] ==1)return false; Else++ROW[BOARD[I][J]-'1']; intK = I/3*3+ J/3; if(Cub[k][board[i][j]-'1'] ==1)return false; Else++CUB[K][BOARD[I][J]-'1']; } if(Board[j][i]! ='.') { if(Col[board[j][i]-'1'] ==1)return false; Else++col[board[j][i]-'1']; } } } return true; }};
[Lettcode]49. Valid Sudoku Effective Sudoku