Advertisement
shadvoll

sudoku

Mar 12th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. import numpy as np
  2. import copy
  3. import sys
  4. import time
  5. import operator
  6. from termcolor import colored
  7. sys.setrecursionlimit(10000000)
  8.  
  9.  
  10. def printAnswer(matrixIn,MatrixOut):
  11.     print
  12.     for i in range(matrixOut[0].size):
  13.         for j in range(matrixOut[0].size):
  14.             if matrixIn[i][j]==0 and matrixOut[i][j] != 0:
  15.                 text= colored(str(matrixOut[i][j])+' ','red')
  16.                 sys.stdout.write(text)
  17.             else:
  18.                 sys.stdout.write(str(matrixOut[i][j])+' ')
  19.         print
  20.     print
  21.  
  22. def get_row(array, index):
  23.     return array[index]
  24.  
  25. def get_column(array, index):
  26.     return array[:, index]
  27.  
  28. def get_tile(array,index_row,index_column):
  29.     row=index_row-(index_row-int(index_row/3)*3)
  30.     column=index_column-(index_column-int(index_column/3)*3)
  31.     return array[row:row+3, column:column+3]
  32.  
  33. def ifSolved(matrixIn,matrixOut):
  34.     index = 80
  35.     i = index // 9
  36.     j = index % 9
  37.     while matrixIn[i][j] != 0:
  38.         index -= 1
  39.         i = index // 9
  40.         j = index % 9
  41.     if matrixOut[i][j] != 0:
  42.         return True
  43.     else:
  44.         return False
  45.  
  46. def solve(matrixIn,matrixOut,index):
  47.     if index  == 81:
  48.         printAnswer(matrixIn,matrixOut)
  49.         return matrixOut
  50.     i = index // 9
  51.     j = index % 9
  52.     # printAnswer(matrixIn,matrixOut)
  53.     if matrixIn[i][j] == 0 :
  54.         for k in range(1,10):
  55.             if ifSolved(matrixIn,matrixOut):
  56.                 return matrixOut
  57.             if not (k in get_row(matrixOut,i) or k in get_column(matrixOut,j) or k in get_tile(matrixOut,i,j)):
  58.                 matrixOut[i][j] = k
  59.                 solve(matrixIn,matrixOut,index+1)
  60.         matrixOut[i][j]=0
  61.     else:
  62.         return solve(matrixIn,matrixOut,index+1)
  63.  
  64. matrixIn=np.loadtxt("sudoku-task0.txt")
  65. matrixOut=copy.copy(matrixIn)
  66. matrixOutFinal=copy.copy(matrixIn)
  67.  
  68. print('Matrix of input')
  69. print(matrixIn)
  70. print('Answer')
  71. t1 = time.clock()
  72. matrixOutFinal = solve(matrixIn,matrixOut,0)
  73. t2 = time.clock()
  74. print str(t2-t1)+' '+'sec'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement