Created
April 1, 2021 03:04
-
-
Save tanmayb123/2beea3aad54f30bb502e22d86509d27f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
struct SudokuBoard { | |
var board: [Int] | |
subscript(_ x: Int, _ y: Int) -> Int { | |
get { | |
return board[y * 9 + x] | |
} | |
set { | |
board[y * 9 + x] = newValue | |
} | |
} | |
init(board: [[Int]]) { | |
self.board = [Int](repeating: 0, count: 9 * 9) | |
for y in 0..<9 { | |
for x in 0..<9 { | |
self[x, y] = board[y][x] | |
} | |
} | |
} | |
func isValid(number: Int, at point: (x: Int, y: Int)) -> Bool { | |
for i in 0..<9 { | |
if self[point.x, i] == number { return false } | |
if self[i, point.y] == number { return false } | |
} | |
for x in 0..<3 { | |
for y in 0..<3 { | |
if self[(point.x / 3) * 3 + x, (point.y / 3) * 3 + y] == number { return false } | |
} | |
} | |
return true | |
} | |
func children() -> [SudokuBoard]? { | |
guard let idx = board.firstIndex(of: 0) else { | |
return nil | |
} | |
var children: [SudokuBoard] = [] | |
for i in 1...9 { | |
if isValid(number: i, at: (idx % 9, idx / 9)) { | |
var newBoard = self | |
newBoard.board[idx] = i | |
children.append(newBoard) | |
} | |
} | |
return children | |
} | |
func solve() -> SudokuBoard? { | |
guard let children = children() else { | |
return self | |
} | |
if children.isEmpty { | |
return nil | |
} | |
for child in children { | |
if let solution = child.solve() { | |
return solution | |
} | |
} | |
return nil | |
} | |
} | |
let board = SudokuBoard(board: [ | |
[0, 0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0, 0], | |
]) | |
if let solution = board.solve() { | |
for y in 0..<9 { | |
for x in 0..<9 { | |
print(solution[x, y], terminator: "|") | |
} | |
print("\n\([String](repeating: "-", count: 17).joined())") | |
} | |
print("\n\n") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment