LeetCode36: Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles-The Rules.
The Sudoku board cocould 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.
At first glance, this question is to exchange space for time. Under normal circumstances, each row should be compared, each column should be compared, and then each grid should be compared, but each comparison has a double-layer loop.
You can use the set in STL to determine whether the element already exists. A typical space exchange time method is used.
Runtime: 24 ms
Class Solution {public: bool isValidSudoku (vector
> & Board) {unordered_set
Rows [9]; // each row has a set to determine whether there is a duplicate element unordered_set in the modified row.
Columns [9]; // a set in each column is used to determine whether a duplicate element unordered_set exists in the column.
Grids [3] [3]; // each 3*3 grid has a set to determine whether the grid has repeated elements for (int I = 0; I <9; I ++) {for (int j = 0; j <9; j ++) {if (board [I] [j]! = '.') {Char tmp = board [I] [j]; if (! Rows [I]. insert (tmp). second |! Columns [j]. insert (tmp). second |! Grids [I/3] [j/3]. insert (tmp). second) return false ;}} return true ;}};
In addition to STL, you can define a mask in the same way as above.
Use an int rows [9] [9] to record the row mask.
Use an int column [9] [9] to record the column mask
Use an int gird [3] [3] [9] to record the mesh mask.
Runtime: 12 ms
Half of the running time !!!!
class Solution {public: bool isValidSudoku(vector
>& board) { int rows[9][9]={0}; int columns[9][9]={0}; int grids[3][3][9]={0}; for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { if(board[i][j]!='.') { char tmp=board[i][j]; int index=tmp-'1'; if(rows[i][index]++) return false; if(columns[j][index]++) return false; if(grids[i/3][j/3][index]++) return false; } } } return true; } };