Valid Sudoku leetcode java
题目:
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的唯一性来帮助check。
先按每行check,如果是'.'说明还没填字,是合法的,往下走,如果没在set中存过就加一下,如果便利过程中出现了在set中存在的key值,说明有重复的数字在一行,不合法,return false。
再按照这个方法check列。
最后按照这个方法check小方块。
注意小方块的ij取法。对于当前这块板子来说,总共有9个小方格,按0~8从左到右依次编号。
按编号求'/'就是求得当前小方格的第一行横坐标,因为每个小方格有3行,所以循环3次。
按编号求'%'就是求得当前小方格的第一列纵坐标,因为每个小方格有3列,所以循环3次。
对9个小方格依次走一边,就完成了检查小方格的工作。
代码如下:
1 public boolean isValidSudoku(char[][] board) {
2 HashSet<Character> set = new HashSet<Character>();
3 // Check for each row
4 for (int i = 0; i < 9; i++) {
5 for (int j = 0; j < 9; j++) {
6 if (board[i][j] == '.')
7 continue;
8 if (set.contains(board[i][j]))
9 return false;
10 set.add(board[i][j]);
11 }
12 set.clear();
13 }
14
15 // Check for each column
16 for (int j = 0; j < 9; j++) {
17 for (int i = 0; i < 9; i++) {
18 if (board[i][j] == '.')
19 continue;
20 if (set.contains(board[i][j]))
21 return false;
22 set.add(board[i][j]);
23 }
24 set.clear();
25 }
26
27 // Check for each sub-grid
28 for (int k = 0; k < 9; k++) {
29 for (int i = k/3*3; i < k/3*3+3; i++) {
30 for (int j = (k%3)*3; j < (k%3)*3+3; j++) {
31 if (board[i][j] == '.')
32 continue;
33 if (set.contains(board[i][j]))
34 return false;
35 set.add(board[i][j]);
36 }
37 }
38 set.clear();
39 }
40
41 return true;
42 }
2 HashSet<Character> set = new HashSet<Character>();
3 // Check for each row
4 for (int i = 0; i < 9; i++) {
5 for (int j = 0; j < 9; j++) {
6 if (board[i][j] == '.')
7 continue;
8 if (set.contains(board[i][j]))
9 return false;
10 set.add(board[i][j]);
11 }
12 set.clear();
13 }
14
15 // Check for each column
16 for (int j = 0; j < 9; j++) {
17 for (int i = 0; i < 9; i++) {
18 if (board[i][j] == '.')
19 continue;
20 if (set.contains(board[i][j]))
21 return false;
22 set.add(board[i][j]);
23 }
24 set.clear();
25 }
26
27 // Check for each sub-grid
28 for (int k = 0; k < 9; k++) {
29 for (int i = k/3*3; i < k/3*3+3; i++) {
30 for (int j = (k%3)*3; j < (k%3)*3+3; j++) {
31 if (board[i][j] == '.')
32 continue;
33 if (set.contains(board[i][j]))
34 return false;
35 set.add(board[i][j]);
36 }
37 }
38 set.clear();
39 }
40
41 return true;
42 }