-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudoku.py
83 lines (74 loc) · 2.07 KB
/
sudoku.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
import numpy as np
import time
def validNumber(number, rowNumber, columnNumber):
global sudoku
if number in sudoku[rowNumber]:
return 0
if number in sudoku[:,columnNumber]:
return 0
for row in sudoku[rowNumber//3*3:(rowNumber+1)//3*3,columnNumber//3*3:(columnNumber+1)//3*3]:
if number in row:
return 0
return 1
def solveSudoku():
iterations = 0
millis = time.time()
count = 0
while count < 81:
i, j = count//9, count%9
state = 1
num = sudoku[i][j]
while not sudokuState[i][j] and state:
iterations+=1
if num < 9:
num += 1
if (num < 10 and validNumber(num, i, j)):
sudoku[i][j] = num
state = 0
count += 1
i, j = count//9, count%9
break
elif num == 9 and not validNumber(num, i, j):
sudoku[i][j] = 0
count -= 1
i, j = count//9, count%9
while sudokuState [i][j]:
count -= 1
i, j = count//9, count%9
break
if count < 81 and sudokuState[i][j]:
count += 1
i, j = count//9, count%9
print ('evaluation time in seconds:', time.time() - millis)
print ("number of iterations :",iterations)
print()
for i in range(9):
print(end=" ")
for j in range(9):
print (sudoku[i][j],end="|")
if (j+1)%3 == 0:
print (end="\b ")
if (i+1)%3:
print("\n-----------------------")
else:
print("\n")
mat = input("enter numbers")
sudoku = []
for i in mat.split(" "):
row = []
# print (list(i))
for j in i:
row.append(int(j))
sudoku.append(row)
sudoku = np.array(sudoku)
print (sudoku)
sudokuState = []
for row in sudoku:
state = []
for element in row:
if element == 0:
state.append(0)
else:
state.append(1)
sudokuState.append(state)
solveSudoku()