Created
April 21, 2018 17:40
-
-
Save jianminchen/5d1d13e8128fd5614acfce634879bb09 to your computer and use it in GitHub Desktop.
Suodku solver - swift - being an interviewer 10:00 am - April 21, 2018
This file contains 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
//5 3 . | |
//6, . . | |
//. 9 8 | |
// for eaech row | |
// for column | |
// if != "." { | |
// | |
import Foundation | |
func sudokuSolve(board: [[Character]]) -> Bool { | |
var grid = board | |
for i in 0..<board.count { | |
for j in 0..<board[0].count { | |
if board[i][j] == "." { | |
for n in 1..<10 { | |
if isClear(Character(String(n)), i,j,&grid) { | |
grid[i][j] = Character(String(n)) | |
if sudokuSolve(board: grid) { | |
return true | |
} else { | |
grid[i][j] = "." | |
} | |
} | |
} | |
return false | |
} | |
} | |
} | |
return true | |
} | |
func isClear(_ num: Character,_ r: Int,_ c: Int,_ board: inout [[Character]]) -> Bool { | |
for i in 0..<board.count { | |
if board[r][i] != "." && board[r][i] == num { | |
return false | |
} | |
if board[i][c] != "." && board[i][c] == num { | |
return false | |
} | |
let row = 3 * (r / 3) + i / 3 | |
let column = 3 * (c / 3) + i % 3 | |
if board[row][column] != "." && board[row][column] == num { | |
return false | |
} | |
} | |
return true | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment