题目描述:
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.
解题思路:
这道题的解题思路比较简单,因为只需要判断已经填入的数字是否合法,那么需要判断每行每列以及每个9宫格的数字是否有重复,很自然的联想到HashSet,因为每个Set里面的元素是不能相同的。顺着这个思路,那么我们为行、列及九宫格各设置9个Hashset元素的数组,每次进行判断即可。
代码如下:
public class Solution { public boolean isValidSudoku(char[][] board) { HashSet[] row = new HashSet[9]; HashSet[] col = new HashSet[9]; HashSet[] cell = new HashSet[9]; for (int i = 0; i < 9; i++) { row[i] = new HashSet<Character>(); col[i] = new HashSet<Character>(); cell[i] = new HashSet<Character>(); } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] != '.') { if (row[i].contains(board[i][j]) || col[j].contains(board[i][j]) || cell[3 * (i / 3) + j / 3].contains(board[i][j])) return false; else { row[i].add(board[i][j]); col[j].add(board[i][j]); cell[3 * (i / 3) + j / 3].add(board[i][j]); } } } } return true; } }