-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolver.py
120 lines (89 loc) · 3.05 KB
/
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
from ultralytics import YOLO
from ultralytics.utils.plotting import Annotator
# Solving Algrothim
def IVM(grid, row, col, number):
for x in range(9):
if grid[row][x] == number:
return False
for x in range(9):
if grid[x][col] == number:
return False
corner_row = row - row % 3
corner_col = col - col % 3
for x in range(3):
for y in range(3):
if grid[corner_row + x][corner_col + y] == number:
return False
return True
def solve(grid, row, col): # Start Solving the puzzle
if col == 9:
if row == 8:
return True
row += 1
col = 0
if grid[row][col] > 0:
return solve(grid, row, col + 1)
for num in range(1,10):
if IVM(grid, row, col, num):
grid[row][col] = num
if solve(grid, row, col + 1):
return True
grid[row][col] = 0
return False
def load_puzzle():
# Load the puzzle from a file
return input("Enter the puzzle: ") # User Input Puzzle
def run_inference(model_file, board_file):
# Load the model and board from files
board_inference = model_file(board_file, verbose=False)
return board_inference
def create_board(bn, orginal_board, model_file):
for nums in range(0,81):
x = bn[0].boxes.xyxyn[nums,0]
y = bn[0].boxes.xyxyn[nums,1]
do_break = False
for test_x in range(0,9):
for test_y in range(0,9):
test_nx = test_x/9
test_ny = test_y/9
if test_nx == 1:
test_nx -= 1/18
if test_ny == 1:
test_ny -= 1/18
if test_nx == 0:
test_nx += 1/18
if test_ny == 0:
test_ny += 1/18
if x > test_nx - 1/18 and x < test_nx + 1/18:
if y > test_ny - 1/18 and y < test_ny + 1/18:
orginal_board[test_x][test_y] = int(model_file.names[int(bn[0].boxes.cls[nums])])
do_break = True
break
if do_break:
break
return orginal_board
def print_sol(the_board):
if solve(the_board, 0, 0):
for i in range(9):
for j in range(9):
print(the_board[i][j], end=" ")
print()
else:
print("No Solution")
def main():
grid = [[ 0, 0, 0, 0, 0, 0, 0, 0, 0], #Predefined Zeroed Grid
[ 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]]
model = YOLO("Pretrained-M.pt")
board = load_puzzle()
board_numbers = run_inference(model, board)
grid = create_board(board_numbers, grid, model)
print_sol(grid)
if __name__ == "__main__":
main()