Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- board = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
- [6, 0, 0, 1, 9, 5, 0, 0, 0],
- [0, 9, 8, 0, 0, 0, 0, 6, 0],
- [8, 0, 0, 0, 6, 0, 0, 0, 3],
- [4, 0, 0, 8, 0, 3, 0, 0, 1],
- [7, 0, 0, 0, 2, 0, 0, 0, 6],
- [0, 6, 0, 0, 0, 0, 2, 8, 0],
- [0, 0, 0, 4, 1, 9, 0, 0, 5],
- [0, 0, 0, 0, 8, 0, 0, 7, 9]]
- #import copy is for allowing to make copy of board
- import copy
- def print_matrix(m):
- #deepcopy is for matrices
- m2 = copy.deepcopy(m)
- print('SUDOKU:')
- line = '-'*25
- #check if empty
- if not m2:
- print('empty')
- #check every element
- for i in range(len(m2)):
- #check if modulo 3 to print line
- if i%3 == 0:
- print(line)
- line_to_print = ''
- for j in range(len(m2[0])):
- if m2[i][j] == 0:
- m2[i][j] = ' '
- #check modulo 3 to add vertical line
- if j%3 == 0:
- line_to_print += '| ' + str(m2[i][j]) + ' '
- else:
- line_to_print += str(m2[i][j]) + ' '
- #print final vertical line and horisontal line
- print(line_to_print+'|')
- print(line)
- def find_zero(board):
- where_zero = []
- #check every element of board
- for i in range(len(board)):
- for j in range(len(board[0])):
- if board[i][j] == 0:
- #append the row to list
- where_zero.append(i)
- #append the colum to list
- where_zero.append(j)
- return where_zero
- return where_zero
- def is_valid(board,row,col,value):
- # check rows
- if value in board[row]:
- return False
- # check colum
- for i in range(len(board)):
- if board[i][col] == value:
- return False
- # check 3*3 board
- new_row = row//3
- new_col = col//3
- # divided by 3 with 2 '//' for exact number
- for i in range(3):
- for j in range(3):
- if board[3*new_row+i][3*new_col+j] == value:
- return False
- return True
- def solve(board):
- #check if empty
- if find_zero(board) == []:
- return board
- else:
- #check every number from 1 to 9
- for i in range(1,10):
- row = find_zero(board)[0]
- col = find_zero(board)[1]
- if is_valid(board,row,col,i):
- board[row][col] = i
- if solve(board) == None:
- board[row][col] = 0
- else:
- return solve(board)
- #print unsoved SUDOKU
- print_matrix(board)
- #print solved SUDOKU
- print_matrix(solve(board))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement