-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolvering.py
113 lines (78 loc) · 2.42 KB
/
solvering.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
#import pdb
import numpy as np
#import time
def main():
#load numpy array from csv two default options of games
#arr=np.loadtxt('sudoeasy.csv', delimiter=',')
arr=np.loadtxt('sudoku.csv', delimiter=',')
#arr=np.loadtxt('unsolvable.csv', delimiter=',')
#cast the array to int for efficiency and leave original array inmutable
board=arr.astype(int)
#global row, col
row=0; col=0;
#check for correct board size
assert arr.size == 81
print ""
print "Sudoku to solve:"
print board
print ""
#start_time=time.time()
if solve(board,row, col) == True:
print "Solution:"
#elapsed_time=time.time()
print board
#print 'Execution time: %.3f' %elapsed_time
else:
print "No solution!"
#looks for blanks (0's)
def findBlanks(board, row, col):
nx, ny = board.shape
for row in xrange(0, nx):
for col in xrange(0, ny):
if board[row,col] == 0 :
return row, col
return False
#check if is not collision in the row with the same number
def checkRow(board, row, num):
slice = board[row,0:9]
for x in slice:
if x == num:
return True
return False
#checks for column for collision with the same number
def checkCol(board, col, num):
slice = board[0:9,col]
for x in slice:
if x == num:
return True
return False
def checkBox(board, rowpos, colpos, num):
#pdb.set_trace()
for row in xrange(0, 3):
for col in xrange(0, 3):
if board[row+rowpos][col+colpos] == num :
return True
return False
def checks(board, row, col, num):
return not checkRow(board, row, num) and not checkCol(board, col, num) and not checkBox(board, row-(row%3), col-(col%3), num)
#solve sudoku function
def solve(board, row, col):
row
col
#find the blank spaces to fill (0's)
if not findBlanks(board, row, col):
return True
find = findBlanks(board, row, col)
row=find[0]; col=find[1]
#start trying numbers in blanks
for num in xrange(1,10):
#checks if is valid
if checks(board, row, col, num):
board[row,col] = num
if solve(board, row, col):
#if solve(board):
return True
board[row,col] = 0
return False
if __name__ == "__main__":
main()