Problem description
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits 1-9 without repetition.
- Each column must contain the digits 1-9 without repetition.
- Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.
Examples
1 | Example 1: |
1 | Example 2: |
Solution
用3个HashSet,分别保存第i行、第i列和第i个3x3的九宫格(i个九宫格也是从0开始)中的元素,每处理一个元素,若不为空,将正在处理的当前元素,添加到所属的行、列以及3x3的九宫格中,若添加失败,表明所属的行、列或者3x3九宫格中有重复元素,返回false;若全部扫描完,返回true。九宫格的行列转换代码没想出来。
( i / 3 ) x 3 得到九宫格的起始行数即九宫格左上角块所处行。( i / 3 ) * 3 + j / 3得到九宫格中任一对应行(PS: 0 <= j <= 8)。
( i % 3) x 3 得到九宫格起始列数即九宫格左上角所处列。i % 3 * 3 + j % 3得到九宫格中任一对应列(PS: 0 <= j <= 8)。
Code
1 | public boolean isValidSudoku(char[][] board) { |