Determine if a Sudoku is valid, according To:sudoku puzzles-the Rules. (http://sudoku.com.au/TheRules.aspx)
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.
Solution 1:
Check each row, each column, and each of the nine Gongge to see if duplicate elements appear with a map record with a key unique attribute. The difficulty lies in the inspection of the ninth Gongge
Observe the law of line numbers:
No. 0 Nine Gongge: 000111222; 1th Nine Gongge: 000111222; 2nd nine Gongge: 000111222;
3rd nine Gongge: 333444555; 4th nine Gongge: 333444555; 5th nine Gongge: 333444555;
6th nine Gongge: 666777888; 7th nine Gongge: 666777888; 8th nine Gongge: 666777888;
Visible for each of the three nine Gonge increase 3, for a single nine Gongge, every three lattice line number 1.
Therefore, the row number of the J-point of the ninth Gongge can be expressed as a I/3*3+J/3
Observe the rule of the column number:
No. 0 Nine Gongge: 012012012; 1th Nine Gongge: 345345345; 2nd nine Gongge: 678678678;
3rd nine Gongge: 012012012; 4th nine Gongge: 345345345; 5th nine Gongge: 678678678;
6th nine Gongge: 012012012; 7th nine Gongge: 345345345; 8th nine Gongge: 678678678;
Visible for the next nine Gongrie increase 3, the cycle period is 3, for a single nine Gongge, each lattice point line number 1, the period is 3.
The mathematical representation of a cycle is the modulo operation MoD.
Therefore, the column number of the J-point of the ninth Gongge can be expressed as a i%3*3+j%3
1 classSolution {2 Public:3 BOOLIsvalidsudoku (vector<vector<Char>>&Board) {4 for(inti =0; I <9; i + +)5 {6unordered_map<Char,BOOL>Row; 7unordered_map<Char,BOOL>column; 8unordered_map<Char,BOOL>bod; 9 for(intj =0; J <9; J + +)Ten { One if(Board[i][j]! ='.') A { - if(Row[board[i][j]] = =true)//if ROW[BOARD[I][J]] does not exist, returns 0 - return false; theROW[BOARD[I][J]] =true; - } - if(Board[j][i]! ='.') - { + if(Column[board[j][i]] = =true) - return false; +Column[board[j][i]] =true; A } at if(board[i/3*3+j/3][i%3*3+j%3] !='.') - { - if(bod[board[i/3*3+j/3][i%3*3+j%3]] ==true) - return false; -bod[board[i/3*3+j/3][i%3*3+j%3]] =true; - } in } - } to return true; + } -};
Solution 2: The solution to the cock dick seen on the discussion
1 classSolution2 {3 Public:4 BOOLIsvalidsudoku (vector<vector<Char> > &Board)5 {6 intused1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0};7 8 for(inti =0; I < board.size (); ++i)9 for(intj =0; J < Board[i].size (); ++j)Ten if(Board[i][j]! ='.') One { A intnum = board[i][j]-'0'-1, k = I/3*3+ J/3; - if(Used1[i][num] | | used2[j][num] | |Used3[k][num]) - return false; theUsed1[i][num] = Used2[j][num] = Used3[k][num] =1; - } - - return true; + } -};
"Leetcode" 36-valid Sudoku