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.
Judge Nine Gongge rationality (and not necessarily have the solution), only need to Judge row, column, 9 sub-nine Gongge is reasonable can!
My thinking is very conventional, code efficiency is slow, as follows:
1 classSolution {2 Public:3 BOOLIsvalidsudoku (vector<vector<Char>>&Board) {4map<Char,int>Mark;5 for(intI=0;i<9; i++)6 {7 mark.clear ();8 for(intj=0;j<9; j + +)//whether the line is reasonable9 {Tenmark[board[i][j]]++; One if(board[i][j]!='.'&&mark[board[i][j]]>1) A return false; - } - mark.clear (); the for(intj=0;j<9; j + +)//whether the column is reasonable - { -mark[board[j][i]]++; - if(board[j][i]!='.'&&mark[board[j][i]]>1) + return false; - } + } A for(intI=0;i<3; i++)//Check 9 sub-nine Gongge, control the line. 3 Rows (or 3 columns) each time, I choose a row or a total of 3 rows from the top, one row at a time at { - mark.clear (); - for(intj=3*i;j<3*i+3; j + +)//first column - for(intk=0;k<3; k++) - { -mark[board[j][k]]++; in if(board[j][k]!='.'&&mark[board[j][k]]>1) - return false; to } + mark.clear (); - for(intj=3*i;j<3*i+3; j + +)//second column the for(intk=3;k<6; k++) * { $mark[board[j][k]]++;Panax Notoginseng if(board[j][k]!='.'&&mark[board[j][k]]>1) - return false; the } + mark.clear (); A for(intj=3*i;j<3*i+3; j + +)//third column the for(intk=6;k<9; k++) + { -mark[board[j][k]]++; $ if(board[j][k]!='.'&&mark[board[j][k]]>1) $ return false; - } - } the return true; - }Wuyi};
Valid Sudoku Leetcode