Created
September 20, 2017 10:07
-
-
Save SauravKanchan/6015a59d714290aefc2ff504061fe973 to your computer and use it in GitHub Desktop.
Sudoku Solver wriiten in python
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
cell=[] | |
[cell.append(list(map(int,input().split()))) for _ in range(9)]#Take the given sudoku. | |
def Blank():#Search for blank(or 0's) in cell.Give cordinate of blank cell. | |
for i in range(0, 9): | |
for j in range(0, 9): | |
if cell[i][j] == 0: | |
return [i, j] | |
return [-1, -1] | |
def canPlace(v, y, x):#Return True if v can be placed in (x,y) | |
#Checks for v in that row or column. | |
for i in range(9): | |
if i != x and cell[y][i] == v: | |
return False | |
for i in range(9): | |
if i != y and cell[i][x] == v: | |
return False | |
#Checks for v in particular box | |
by = y - (y % 3) | |
bx = x - (x % 3) | |
for i in range(3): | |
for j in range(3): | |
if by + i != y and bx + j != x and cell[by + i][bx + j] == v: | |
return False | |
return True | |
def solve(): | |
y, x = Blank() | |
if y == -1: #Means it succesfully solved the sudoku. | |
return True | |
for i in range(1, 10): | |
if canPlace(i, y, x): | |
cell[y][x] = i | |
if solve(): | |
return True | |
cell[y][x] = 0 #Whole assumption was false. | |
return False | |
solve() | |
[print(i) for i in cell] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment