-
Notifications
You must be signed in to change notification settings - Fork 2
/
backtracking.py
59 lines (50 loc) · 1.7 KB
/
backtracking.py
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
import numpy as np
def printBoard(b):
for row in b:
print(" ".join(row))
class Solution:
def solveSudoku(self, board):
self.board = board
self.solve()
def findUnassigned(self):
for row in range(9):
for col in range(9):
if self.board[row][col] == ".":
return row, col
return -1, -1
def solve(self):
row, col = self.findUnassigned()
if row == -1 and col == -1:
return True
for num in "123456789":
if self.isSafe(row, col, num):
self.board[row][col] = num
if self.solve():
return True
self.board[row][col] = "."
return False
def isSafe(self, row, col, ch):
boxrow = row - row % 3
boxcol = col - col % 3
return (self.checkrow(row, ch) and
self.checkcol(col, ch) and
self.checksquare(boxrow, boxcol, ch))
def checkrow(self, row, ch):
return all(self.board[row][col] != ch for col in range(9))
def checkcol(self, col, ch):
return all(self.board[row][col] != ch for row in range(9))
def checksquare(self, row, col, ch):
return all(self.board[r][c] != ch
for r in range(row, row + 3)
for c in range(col, col + 3))
def backtracking(board):
b = np.array(board).reshape(9, 9).tolist()
print("\nInput board\n")
printBoard(b)
s = Solution()
solved = s.solveSudoku(b) # Make sure this returns True when solved.
print("\nOutput board\n")
if solved:
printBoard(s.board)
else:
print("No solution exists for the given Sudoku board.")