题目链接:https://leetcode.com/problems/valid-sudoku/
题目:
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are 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.
思路:
每行、每列、每个黑粗线内小方块的数分别用HashSet保存判断是否唯一。
算法:
-
</pre><pre name="code" class="java"> public boolean isValidSudoku(char[][] board) {
-
Set<Character> row = new HashSet<Character>();
-
Set<Character> column = new HashSet<Character>();
-
Set<Character> subBox = new HashSet<Character>();
-
-
for (int i = 0; i < board.length; i++) {
-
for (int j = 0; j < board[0].length; j++) {
-
-
if (board[i][j] != ‘.‘) {
-
if (column.contains(board[i][j])) {
-
return false;
-
} else {
-
column.add(board[i][j]);
-
}
-
}
-
-
}
-
column.clear();
-
}
-
-
-
for (int i = 0; i < board.length; i++) {
-
for (int j = 0; j < board[0].length; j++) {
-
if (board[j][i] != ‘.‘) {
-
if (row.contains(board[j][i])) {
-
return false;
-
} else {
-
row.add(board[j][i]);
-
}
-
}
-
}
-
row.clear();
-
}
-
-
for (int i = 0; i < board.length; i += 3) {
-
for (int j = 0; j < board[0].length; j += 3) {
-
for (int ii = i; ii < i + 3; ii++) {
-
for (int jj = j; jj < j + 3; jj++) {
-
if (board[ii][jj] != ‘.‘) {
-
if (subBox.contains(board[ii][jj])) {
-
return false;
-
} else {
-
subBox.add(board[ii][jj]);
-
}
-
}
-
}
-
}
-
subBox.clear();
-
}
-
}
-
return true;
-
}
【Leetcode】Valid Sudoku
原文:http://blog.csdn.net/yeqiuzs/article/details/51628530