Advertisement
shadvoll

sudoku_simplified

May 28th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 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 get_row(array, index):
  11.     return array[index]
  12.  
  13. def get_column(array, index):
  14.     return array[:, index]
  15.  
  16. def get_tile(array,index_row,index_column):
  17.     row=index_row-(index_row-int(index_row/3)*3)
  18.     column=index_column-(index_column-int(index_column/3)*3)
  19.     return array[row:row+3, column:column+3]
  20.  
  21. def ifSolved(matrixIn,matrixOut):
  22.     index = 80
  23.     i = index // 9
  24.     j = index % 9
  25.     while matrixIn[i][j] != 0:
  26.         index -= 1
  27.         i = index // 9
  28.         j = index % 9
  29.     if matrixOut[i][j] != 0:
  30.         return True
  31.     else:
  32.         return False
  33.  
  34. def solve(matrixIn,matrixOut,index):
  35.     if index  == 81:
  36.         print(matrixOut)
  37.         return matrixOut
  38.     i = index // 9
  39.     j = index % 9
  40.     if matrixIn[i][j] == 0 :
  41.         for k in range(1,10):
  42.             if ifSolved(matrixIn,matrixOut):
  43.                 return matrixOut
  44.             if not (k in get_row(matrixOut,i) or k in get_column(matrixOut,j) or k in get_tile(matrixOut,i,j)):
  45.                 matrixOut[i][j] = k
  46.                 solve(matrixIn,matrixOut,index+1)
  47.         matrixOut[i][j]=0
  48.     else:
  49.         return solve(matrixIn,matrixOut,index+1)
  50.  
  51. matrixIn=np.loadtxt("sudoku-task0.txt")
  52. matrixOut=copy.copy(matrixIn)
  53. matrixOutFinal=copy.copy(matrixIn)
  54.  
  55. print('Matrix of input')
  56. print(matrixIn)
  57. print('Answer')
  58. t1 = time.clock()
  59. matrixOutFinal = solve(matrixIn,matrixOut,0)
  60. t2 = time.clock()
  61. print str(t2-t1)+' '+'sec'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement