Skip to content

Commit fddd5a5

Browse files
author
Yi Gu
committed
Update the solution to the Sudoku Solver
1 parent b3b7f03 commit fddd5a5

File tree

1 file changed

+30
-36
lines changed

1 file changed

+30
-36
lines changed

DFS/SudokuSolver.swift

+30-36
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,34 @@
33
* Primary idea: Iterate through the whole matrix, try to fill out empty space with all
44
* possible cases and check the vaildity
55
*
6-
* Time Complexity: O(n^4), Space Complexity: O(1)
6+
* Time Complexity: O((9!) ^ 9), Space Complexity: O(1)
77
*/
88

9-
class SudokuSolver {
9+
10+
class SudokuSolver {
11+
private let length = 9
12+
1013
func solveSudoku(_ board: inout [[Character]]) {
11-
guard board.count != 0 || board[0].count != 0 else {
12-
return
13-
}
14-
helper(&board)
14+
dfs(&board)
1515
}
1616

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 {
2222
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) {
2828
return true
29-
} else {
30-
board[i][j] = "."
3129
}
30+
board[i][j] = "."
3231
}
3332
}
33+
3434
return false
3535
}
3636
}
@@ -40,31 +40,25 @@
4040
}
4141

4242
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 {
4847
return false
4948
}
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 {
5552
return false
5653
}
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
6558
}
6659
}
6760

6861
return true
6962
}
63+
}
7064
}

0 commit comments

Comments
 (0)