Advertisement
yragi_san

solve sudoku python program

Sep 24th, 2020
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. board = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
  2. [6, 0, 0, 1, 9, 5, 0, 0, 0],
  3. [0, 9, 8, 0, 0, 0, 0, 6, 0],
  4. [8, 0, 0, 0, 6, 0, 0, 0, 3],
  5. [4, 0, 0, 8, 0, 3, 0, 0, 1],
  6. [7, 0, 0, 0, 2, 0, 0, 0, 6],
  7. [0, 6, 0, 0, 0, 0, 2, 8, 0],
  8. [0, 0, 0, 4, 1, 9, 0, 0, 5],
  9. [0, 0, 0, 0, 8, 0, 0, 7, 9]]
  10.  
  11. #import copy is for allowing to make copy of board
  12. import copy
  13. def print_matrix(m):
  14. #deepcopy is for matrices
  15. m2 = copy.deepcopy(m)
  16. print('SUDOKU:')
  17. line = '-'*25
  18. #check if empty
  19. if not m2:
  20. print('empty')
  21. #check every element
  22. for i in range(len(m2)):
  23. #check if modulo 3 to print line
  24. if i%3 == 0:
  25. print(line)
  26. line_to_print = ''
  27. for j in range(len(m2[0])):
  28. if m2[i][j] == 0:
  29. m2[i][j] = ' '
  30. #check modulo 3 to add vertical line
  31. if j%3 == 0:
  32. line_to_print += '| ' + str(m2[i][j]) + ' '
  33. else:
  34. line_to_print += str(m2[i][j]) + ' '
  35. #print final vertical line and horisontal line
  36. print(line_to_print+'|')
  37. print(line)
  38.  
  39. def find_zero(board):
  40. where_zero = []
  41. #check every element of board
  42. for i in range(len(board)):
  43. for j in range(len(board[0])):
  44. if board[i][j] == 0:
  45. #append the row to list
  46. where_zero.append(i)
  47. #append the colum to list
  48. where_zero.append(j)
  49. return where_zero
  50. return where_zero
  51.  
  52. def is_valid(board,row,col,value):
  53. # check rows
  54. if value in board[row]:
  55. return False
  56. # check colum
  57. for i in range(len(board)):
  58. if board[i][col] == value:
  59. return False
  60. # check 3*3 board
  61. new_row = row//3
  62. new_col = col//3
  63. # divided by 3 with 2 '//' for exact number
  64. for i in range(3):
  65. for j in range(3):
  66. if board[3*new_row+i][3*new_col+j] == value:
  67. return False
  68. return True
  69.  
  70. def solve(board):
  71. #check if empty
  72. if find_zero(board) == []:
  73. return board
  74. else:
  75. #check every number from 1 to 9
  76. for i in range(1,10):
  77. row = find_zero(board)[0]
  78. col = find_zero(board)[1]
  79. if is_valid(board,row,col,i):
  80. board[row][col] = i
  81. if solve(board) == None:
  82. board[row][col] = 0
  83. else:
  84. return solve(board)
  85.  
  86. #print unsoved SUDOKU
  87. print_matrix(board)
  88. #print solved SUDOKU
  89. print_matrix(solve(board))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement