Topic
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.
Analysis
This is a topic about Sudoku, first of all to understand the rules of Sudoku game:
So, for this topic, some of the blanks are '. ' characters, we just need to consider whether the current state satisfies the Sudoku.
That is, we are going to test three times by row, by column, by each 3*3 Gongge.
AC Code
classSolution { Public:BOOLIsvalidsudoku ( vector<vector<char>>& Board) {if(Board.empty ())return false;//Sudoku game in accordance with 9 Gongge, that is, a 9*9 matrix intSize = Board.size ();//According to the rules of Sudoku game, three Tests are required (by row, by column, by 3*3 block) //Using the idea of hashing, record the number of occurrences of each keyword, and return False if the number of times >1 vector<int>Count for(inti =0; i < size; ++i) {The vector of the number of records is zeroed by the beginning of each line, and the element 1~9 corresponds to the subscript 0~8, corresponding to the number of occurrences of the element in the vector .Count.assign (9,0); for(intj =0; J < size; J + +) {if(Board[i][j]! ='. ') {intpos = board[i][j]-' 1 ';if(Count[pos] >0)return false;Else++count[pos]; }Else Continue; }//for}//for //The same, by column inspection for(intj =0; J < size; J + +) {count.assign (9,0); for(inti =0; i < size; i++) {if(Board[i][j]! ='. ') {intpos = board[i][j]-' 1 ';if(Count[pos] >0)return false;Else++count[pos];; }Else Continue; }//for}//for //Press 3*3 small piece inspection for(inti =0; i < size; i + =3) { for(intj =0; J < size; J + =3) {Count.assign (9,0);//Each block is also a 3*3 matrix for(introw = i; Row < i +3; row++) for(intcol = j; Col < J +3; col++) {if(Board[row][col]! ='. ') {intpos = Board[row][col]-' 1 ';if(Count[pos] >0)return false;Else++count[pos];; }Else Continue; } }//for}//for return true; } };
GitHub test Program source code
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode (Valid) Sudoku