Sudoku Solver Program in Python
Sudoku is a number puzzle which makes the arrangement in particular order in a square.
Logic:
- Let us consider 1 to 9 number.
- Plan a table for 9 rows and 9 columns.
- Each 3x3 row and column’s consider a part. So there are 9 parts.
- There are two things to be considered.
- First, each row and each column should have the number 1 to 9 at least once. But same number should not be repeated.
- Next, each part should have the number 1 to 9.
Python implementation:
def ch_valid(board1, s_row, s_col, n):
for i in range(9):
if
board1[s_row][i] == n or board1[i][s_col] == n:
return
False
start_row,
start_col = 3 * (s_row // 3), 3 * (s_col // 3)
for i in range(3):
for j in
range(3):
if
board1[start_row + i][start_col + j] == n:
return
False
return True
def solveit_sudoku(board1):
for s_row in
range(9):
for s_col in
range(9):
if
board1[s_row][s_col] == 0:
for n
in range(1, 10):
if
ch_valid(board1, s_row, s_col, n):
board1[s_row][s_col] = n
if solveit_sudoku(board1):
return True
board1[s_row][s_col] = 0
return
False
return True
def display_board(board1):
for s_row in
board1:
print("
".join(str(n) for n in s_row))
def main():
board1 = [
[0, 3, 4, 0,
0, 8, 0, 1, 0],
[6, 0, 2, 1,
0, 5, 0, 4, 0],
[0, 9, 0, 3,
0, 2, 0, 6, 0],
[0, 5, 0, 7,
6, 0, 0, 0, 3],
[4, 0, 6, 8,
0, 0, 7, 0, 1],
[7, 0, 3, 0,
0, 4, 8, 0, 6],
[0, 6, 0, 5,
0, 7, 0, 8, 0],
[0, 8, 0, 4,
0, 9, 6, 0, 5],
[0, 0, 5, 2,
0, 0, 1, 7, 0]
]
print("The Original Sudoku is shown in output:")
display_board(board1)
print("\nSolved Sudoku is given below:")
if
solveit_sudoku(board1):
display_board(board1)
else:
print("No
solution exists")
if __name__ == "__main__":
main()
Output:
C:\raji>py sudoku.py
The Original Sudoku is shown in output:
0 3 4 0 0 8 0 1 0
6 0 2 1 0 5 0 4 0
0 9 0 3 0 2 0 6 0
0 5 0 7 6 0 0 0 3
4 0 6 8 0 0 7 0 1
7 0 3 0 0 4 8 0 6
0 6 0 5 0 7 0 8 0
0 8 0 4 0 9 6 0 5
0 0 5 2 0 0 1 7 0
Solved Sudoku is given below:
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
That’s all. The implementation of sudoku in python was written
successfully. Keep coding!!!
Comments
Post a Comment