Skip to content

Instantly share code, notes, and snippets.

@tanmayb123
Created April 1, 2021 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanmayb123/2beea3aad54f30bb502e22d86509d27f to your computer and use it in GitHub Desktop.
Save tanmayb123/2beea3aad54f30bb502e22d86509d27f to your computer and use it in GitHub Desktop.
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