Advertisement
Deozaan

Python Sudoku Solver

Jun 23rd, 2020 (edited)
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. import numpy as np
  2.  
  3. grid = [[0,0,0,0,0,7,0,8,0],
  4.         [4,0,8,0,0,0,0,9,0],
  5.         [0,7,0,0,0,0,0,2,1],
  6.         [2,0,4,3,0,5,0,0,0],
  7.         [0,0,0,6,0,4,0,0,0],
  8.         [0,0,0,1,0,0,3,0,2],
  9.         [0,3,1,2,0,0,0,0,0],
  10.         [0,0,0,0,0,0,5,0,0],
  11.         [9,0,0,4,6,0,0,0,0]]
  12.        
  13. def possible(y,x,n) :
  14.     global grid
  15.     for i in range(0,9) :
  16.         if grid[y][i] == n :
  17.             return False
  18.     for i in range(0,9) :
  19.         if grid[i][x] == n :
  20.             return False
  21.     x0 = (x//3)*3
  22.     y0 = (y//3)*3
  23.     for i in range(0,3) :
  24.         for j in range(0,3) :
  25.             if grid[y0+i][x0+j] == n :
  26.                 return False
  27.     return True
  28.  
  29. def solve() :
  30.     global grid
  31.     for y in range(9) :
  32.         for x in range(9) :
  33.             if grid[y][x] == 0 :
  34.                 for n in range(1,10) :
  35.                     if possible(y,x,n) :
  36.                         grid[y][x] = n
  37.                         solve()
  38.                         grid[y][x] = 0
  39.                 return
  40.     print(np.matrix(grid))
  41.     return
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement