From 2efaa2782f744cdfd5458082191bf502f1b2107e Mon Sep 17 00:00:00 2001 From: collegecoder25 <113276364+collegecoder25@users.noreply.github.com> Date: Sat, 7 Oct 2023 00:25:37 +0530 Subject: [PATCH] sudoku_solver.py --- sudoku.py | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 sudoku.py diff --git a/sudoku.py b/sudoku.py new file mode 100644 index 0000000..6c8ade4 --- /dev/null +++ b/sudoku.py @@ -0,0 +1,59 @@ +M = 9 +def puzzle(a): + for i in range(M): + for j in range(M): + print(a[i][j],end = " ") + print() +def solve(grid, row, col, num): + for x in range(9): + if grid[row][x] == num: + return False + + for x in range(9): + if grid[x][col] == num: + return False + + + startRow = row - row % 3 + startCol = col - col % 3 + for i in range(3): + for j in range(3): + if grid[i + startRow][j + startCol] == num: + return False + return True + +def Suduko(grid, row, col): + + if (row == M - 1 and col == M): + return True + if col == M: + row += 1 + col = 0 + if grid[row][col] > 0: + return Suduko(grid, row, col + 1) + for num in range(1, M + 1, 1): + + if solve(grid, row, col, num): + + grid[row][col] = num + if Suduko(grid, row, col + 1): + return True + grid[row][col] = 0 + return False + +'''0 means the cells where no value is assigned''' +grid = [ + [0, 5, 0, 0, 0, 0, 0, 0, 7], + [6, 9, 4, 0, 0, 7, 8, 0, 0], + [0, 7, 3, 0, 0, 6, 1, 0, 9], + [0, 1, 0, 0, 0, 0, 0, 3, 0], + [3, 6, 9, 0, 0, 0, 0, 0, 1], + [5, 0, 0, 9, 1, 0, 0, 0, 0], + [0, 3, 0, 0, 6, 0, 4, 1, 0], + [0, 4, 0, 3, 0, 0, 7, 0, 0], + [7, 2, 0, 0, 0, 5, 0, 0, 0]] + +if (Suduko(grid, 0, 0)): + puzzle(grid) +else: + print("Solution does not exist:(")