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 following:
This problem uses the uniqueness of HashSet to help check.
Press each line check first, if it is '. ' Description has not been filled, is legal, go down, if not in the set to add a bit, if the convenience process appears in set in the key value, indicating that there is a duplicate number in a row, illegal, return false.
Then follow this method check column.
Finally, check the small squares in this way.
Notice the IJ of the small squares. For the current board, there are a total of 9 small squares, which are numbered from left to right by 0~8.
by number "/" is to find the current small square of the first line of the horizontal axis, because each small square has 3 rows, so the loop 3 times.
"%" by number is the first column of the current small square ordinate, because each small square has 3 columns, so the loop 3 times.
On the other side of the 9 small squares, we completed the work of checking the squares.
Code:
public class Validsudoku {
public boolean Isvalidsudoku (char[][] board) {
hashset<character> set = new hashset<character> ();
for (int i = 0; i < 9; i++) {//judging each row
for (int j = 0; J < 9; J + +) {
if (board[i][j] = = '. ')
Continue
if (Set.contains (Board[i][j]))
return false;
Set.add (Board[i][j]);
}
Set.clear ();
}
for (int j = 0; J < 9; J + +) {//Judging each column
for (int i = 0; i < 9; i++) {
if (board[i][j] = = '. ')
Continue
if (Set.contains (Board[i][j]))
return false;
Set.add (Board[i][j]);
}
Set.clear ();
}
for (int k = 0; k < 9; k++) {//Judge every little nine Gongge
for (inti = K/3 * 3; I < K/3 * 3 + 3; i++) {//Nine Gongge lines
for (intj = (k% 3) * 3; J < (k% 3) * 3 + 3; J + +) {//Nine Gongge columns
if (board[i][j] = = '. ')
Continue
if (Set.contains (Board[i][j]))
return false;
Set.add (Board[i][j]);
}
}
Set.clear ();
}
return true;
}
}
Summary: Usage of hashset: http://www.cnblogs.com/kissdodog/archive/2013/02/02/2889887.html
Transferred from: http://www.cnblogs.com/springfor/p/3884217.html
leetcode--Valid Sudoku