-
Notifications
You must be signed in to change notification settings - Fork 889
/
SudokuSolver.swift
64 lines (52 loc) · 1.68 KB
/
SudokuSolver.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Question Link: https://leetcode.com/problems/sudoku-solver/
* Primary idea: Iterate through the whole matrix, try to fill out empty space with all
* possible cases and check the vaildity
*
* Time Complexity: O((9!) ^ 9), Space Complexity: O(1)
*/
class SudokuSolver {
private let length = 9
func solveSudoku(_ board: inout [[Character]]) {
dfs(&board)
}
private func dfs(_ board: inout [[Character]]) -> Bool {
let candidates = "123456789"
for i in 0..<length {
for j in 0..<length {
if board[i][j] == "." {
// place
for candidate in candidates {
if isValid(board, i, j, candidate) {
board[i][j] = candidate
if dfs(&board) {
return true
}
board[i][j] = "."
}
}
return false
}
}
}
return true
}
private func isValid(_ board: [[Character]], _ i: Int, _ j: Int, _ num: Character) -> Bool {
for n in 0..<length {
// check row
if board[n][j] == num {
return false
}
// check column
if board[i][n] == num {
return false
}
// check sub-box
if board[(i / 3) * 3 + n / 3][(j / 3) * 3 + n % 3 ] == num {
return false
}
}
return true
}
}
}