|
| 1 | +#Take Matrix as input |
| 2 | +n=int(input(" Enter no of rows and columns of sudoku problem : ")) |
| 3 | +print("Please enter a ",n,"x",n,"Matrix") |
| 4 | +matrix = [[0 for i in range(n)] for j in range(n)] |
| 5 | +for i in range(0,n): |
| 6 | + for j in range(0,n): |
| 7 | + matrix[i][j] = int(input()) |
| 8 | +# solve matrix which bascially uses two function find_empty() and valid() |
| 9 | +def solve(matrix): |
| 10 | + find = find_empty(matrix) |
| 11 | + # if value of find is false |
| 12 | + if not find: |
| 13 | + return True |
| 14 | + else: |
| 15 | + row, col = find |
| 16 | + # looping through all rows of matrix |
| 17 | + for i in range(1,n+1): |
| 18 | + if valid(matrix, i, (row, col)): |
| 19 | + matrix[row][col] = i |
| 20 | + |
| 21 | + if solve(matrix): |
| 22 | + return True |
| 23 | + |
| 24 | + matrix[row][col] = 0 |
| 25 | + return False |
| 26 | +def valid(matrix, num, pos): |
| 27 | + # Check row |
| 28 | + for i in range(len(matrix[0])): |
| 29 | + if matrix[pos[0]][i] == num and pos[1] != i: |
| 30 | + return False |
| 31 | + # Check column |
| 32 | + for i in range(len(matrix)): |
| 33 | + if matrix[i][pos[1]] == num and pos[0] != i: |
| 34 | + return False |
| 35 | + # Check box |
| 36 | + box_x = pos[1] // 3 |
| 37 | + box_y = pos[0] // 3 |
| 38 | + #looping over the complete matrix |
| 39 | + for i in range(box_y*3, box_y*3 + 3): |
| 40 | + for j in range(box_x * 3, box_x*3 + 3): |
| 41 | + if matrix[i][j] == num and (i,j) != pos: |
| 42 | + return False |
| 43 | + return True |
| 44 | +#function to print the complete sudoku |
| 45 | +def print_board(matrix): |
| 46 | + for i in range(len(matrix)): |
| 47 | + if i % 3 == 0 and i != 0: |
| 48 | + print("- - - - - - - - - - - - - ") |
| 49 | + |
| 50 | + for j in range(len(matrix[0])): |
| 51 | + if j % 3 == 0 and j != 0: |
| 52 | + print(" | ", end="") |
| 53 | + |
| 54 | + if j == 8: |
| 55 | + print(matrix[i][j]) |
| 56 | + else: |
| 57 | + print(str(matrix[i][j]) + " ", end="") |
| 58 | +# function to find whether entered matrix is empty or not |
| 59 | +def find_empty(matrix): |
| 60 | + for i in range(len(matrix)): |
| 61 | + for j in range(len(matrix[0])): |
| 62 | + if matrix[i][j] == 0: |
| 63 | + return (i, j) # row, col |
| 64 | + return None |
| 65 | +print("The entered Matrix for sudoku solver is : ") |
| 66 | +print("") |
| 67 | +print_board(matrix) |
| 68 | +solve(matrix) |
| 69 | +print("") |
| 70 | +print("***********************************************") |
| 71 | +print("") |
| 72 | +print("The output is : ") |
| 73 | +print("") |
| 74 | +print_board(matrix) |
0 commit comments