題目:
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 }