3
3
* Primary idea: Iterate through the whole matrix, try to fill out empty space with all
4
4
* possible cases and check the vaildity
5
5
*
6
- * Time Complexity: O(n^4 ), Space Complexity: O(1)
6
+ * Time Complexity: O((9!) ^ 9 ), Space Complexity: O(1)
7
7
*/
8
8
9
- class SudokuSolver {
9
+
10
+ class SudokuSolver {
11
+ private let length = 9
12
+
10
13
func solveSudoku( _ board: inout [ [ Character ] ] ) {
11
- guard board. count != 0 || board [ 0 ] . count != 0 else {
12
- return
13
- }
14
- helper ( & board)
14
+ dfs ( & board)
15
15
}
16
16
17
- private func helper ( _ board: inout [ [ Character ] ] ) -> Bool {
18
- let m = board . count , n = board [ 0 ] . count
19
-
20
- for i in 0 ..< m {
21
- for j in 0 ..< n {
17
+ private func dfs ( _ board: inout [ [ Character ] ] ) -> Bool {
18
+ let candidates = " 123456789 "
19
+
20
+ for i in 0 ..< length {
21
+ for j in 0 ..< length {
22
22
if board [ i] [ j] == " . " {
23
- for num in 1 ... 9 {
24
- if isValid ( board , i , j , Character ( String ( num ) ) ) {
25
- board [ i ] [ j ] = Character ( String ( num ) )
26
-
27
- if helper ( & board) {
23
+ // place
24
+ for candidate in candidates {
25
+ if isValid ( board, i , j , candidate ) {
26
+ board [ i ] [ j ] = candidate
27
+ if dfs ( & board) {
28
28
return true
29
- } else {
30
- board [ i] [ j] = " . "
31
29
}
30
+ board [ i] [ j] = " . "
32
31
}
33
32
}
33
+
34
34
return false
35
35
}
36
36
}
40
40
}
41
41
42
42
private func isValid( _ board: [ [ Character ] ] , _ i: Int , _ j: Int , _ num: Character ) -> Bool {
43
- let m = board. count, n = board [ 0 ] . count
44
-
45
- // check row
46
- for x in 0 ..< n {
47
- if board [ i] [ x] == num {
43
+
44
+ for n in 0 ..< length {
45
+ // check row
46
+ if board [ n] [ j] == num {
48
47
return false
49
48
}
50
- }
51
-
52
- // check col
53
- for y in 0 ..< m {
54
- if board [ y] [ j] == num {
49
+
50
+ // check column
51
+ if board [ i] [ n] == num {
55
52
return false
56
53
}
57
- }
58
-
59
- // check square
60
- for x in i / 3 * 3 ..< i / 3 * 3 + 3 {
61
- for y in j / 3 * 3 ..< j / 3 * 3 + 3 {
62
- if board [ x] [ y] == num {
63
- return false
64
- }
54
+
55
+ // check sub-box
56
+ if board [ ( i / 3 ) * 3 + n / 3 ] [ ( j / 3 ) * 3 + n % 3 ] == num {
57
+ return false
65
58
}
66
59
}
67
60
68
61
return true
69
62
}
63
+ }
70
64
}
0 commit comments