-
Notifications
You must be signed in to change notification settings - Fork 1
/
Backtracking_Solver.py
56 lines (43 loc) · 1.43 KB
/
Backtracking_Solver.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
import numpy as np
#sudoku = input("Enter Soduku")
#sudoku= 070000009510420600080300700008001370023080040400900100962800030000010400700203096
#puz = [[int(sudoku[(i+j)-1]) for i in range(1,10)] for j in range(0,81,9)]
unsolved = np.array(
[3, 9, 6,1, 8, 0, 7, 1, 5, 0, 0, 7, 9, 6, 1, 0, 0, 3, 8, 4, 1, 0, 3, 0, 2, 0, 0, 6, 3, 0, 1, 0, 0, 5, 2, 0, 1, 0,
0, 7, 2, 5, 3, 9, 0, 0, 5, 2, 6, 9, 3, 8, 0, 1, 4, 0, 8, 3, 7, 6, 0, 0, 2, 2, 0, 5, 8, 0, 9, 0, 3, 4, 9, 6, 3, 0,
0, 2, 0, 7, 8])
puz=np.reshape(unsolved, (9, 9))
def check(puzzle, i, row, col):
rows = puzzle[int(row)]
column = [puzzle[r][col] for r in range(0,9,1)]
if i in rows:
return False
if i in column:
return False
SquareRow = (row // 3)*3
squareColumn = (col // 3)*3
Square = [puzzle[y][z] for y in range(SquareRow, SquareRow+3) for z in range(squareColumn, squareColumn+3)]
if i in Square:
return False
return True
def find(puzzle):
for i in range(0,9,1):
for j in range(0,9,1):
if puzzle[i][j]==0:
return i,j
return None
def solve(board):
finds = find(board)
if not finds:
return True
else:
row, col = finds
for i in range(1,10):
if check(board, i, row, col):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
print(solve(puz))
print(puz)