Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import copy
- import sys
- import time
- import operator
- from termcolor import colored
- sys.setrecursionlimit(10000000)
- def printAnswer(matrixIn,MatrixOut):
- print
- for i in range(matrixOut[0].size):
- for j in range(matrixOut[0].size):
- if matrixIn[i][j]==0 and matrixOut[i][j] != 0:
- text= colored(str(matrixOut[i][j])+' ','red')
- sys.stdout.write(text)
- else:
- sys.stdout.write(str(matrixOut[i][j])+' ')
- print
- print
- def get_row(array, index):
- return array[index]
- def get_column(array, index):
- return array[:, index]
- def get_tile(array,index_row,index_column):
- row=index_row-(index_row-int(index_row/3)*3)
- column=index_column-(index_column-int(index_column/3)*3)
- return array[row:row+3, column:column+3]
- def ifSolved(matrixIn,matrixOut):
- index = 80
- i = index // 9
- j = index % 9
- while matrixIn[i][j] != 0:
- index -= 1
- i = index // 9
- j = index % 9
- if matrixOut[i][j] != 0:
- return True
- else:
- return False
- def solve(matrixIn,matrixOut,index):
- if index == 81:
- printAnswer(matrixIn,matrixOut)
- return matrixOut
- i = index // 9
- j = index % 9
- # printAnswer(matrixIn,matrixOut)
- if matrixIn[i][j] == 0 :
- for k in range(1,10):
- if ifSolved(matrixIn,matrixOut):
- return matrixOut
- if not (k in get_row(matrixOut,i) or k in get_column(matrixOut,j) or k in get_tile(matrixOut,i,j)):
- matrixOut[i][j] = k
- solve(matrixIn,matrixOut,index+1)
- matrixOut[i][j]=0
- else:
- return solve(matrixIn,matrixOut,index+1)
- matrixIn=np.loadtxt("sudoku-task0.txt")
- matrixOut=copy.copy(matrixIn)
- matrixOutFinal=copy.copy(matrixIn)
- print('Matrix of input')
- print(matrixIn)
- print('Answer')
- t1 = time.clock()
- matrixOutFinal = solve(matrixIn,matrixOut,0)
- t2 = time.clock()
- print str(t2-t1)+' '+'sec'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement