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.
The problem is to use space in exchange for time, under normal circumstances should be compared each row, each column is compared, and then each grid for comparison, but each comparison has a double-layer loop.
You can use the set in the STL to determine if the element is already present, and the typical space for the time-to-exchange method.
Runtime:24ms
Class Solution {public: bool Isvalidsudoku (vector<vector<char>>& board) { unordered_set< Char> rows[9];//each row a set to determine whether a row has duplicate elements unordered_set<char> columns[9];//Each column A set is used to determine if the column has duplicate elements Unordered_set<char> grids[3][3];//Each of the 3*3 grids a set to determine if the grid has duplicate 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 using STL because this problem is relatively simple, you can use the same way as above to define a mask yourself.
Use an int rows[9][9] to record the line's mask
Use an int column[9][9] to record the mask of the column
Use an int gird[3][3][9] to record the mask of the mesh.
Runtime:12ms
Less than half of the running time!!!
Class Solution {Public:bool Isvalidsudoku (vector<vector<char>>& 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; } };
Leetcode36:valid Sudoku