From 161b22f7497869e59ce2d50a46b9189daaa792db Mon Sep 17 00:00:00 2001 From: Vishakha Date: Sun, 29 Oct 2023 21:34:58 +0530 Subject: [PATCH] Python implementation of a Sudoku puzzle solver using the backtracking algorithm recursive backtracking algorithm to solve Sudoku puzzles. It checks the validity of each move, placing numbers in empty cells while ensuring they follow Sudoku rules. Once a valid solution is found, it returns the solved board. --- Web Development/WeatherAPP/index.html | 77 +++++++++++++++++++-------- sudoku.py | 49 +++++++++++++++++ 2 files changed, 105 insertions(+), 21 deletions(-) create mode 100644 sudoku.py diff --git a/Web Development/WeatherAPP/index.html b/Web Development/WeatherAPP/index.html index 6348d643..4032485b 100644 --- a/Web Development/WeatherAPP/index.html +++ b/Web Development/WeatherAPP/index.html @@ -1,32 +1,67 @@ - - - Document - + Weather App + + + + - -
-
-
- -
+
+ -
- +
+
-
- - - \ No newline at end of file + +
+

Favorite Cities

+ +
+ + + + + + + + + diff --git a/sudoku.py b/sudoku.py new file mode 100644 index 00000000..a60a359b --- /dev/null +++ b/sudoku.py @@ -0,0 +1,49 @@ +def solve_sudoku(board): + def is_valid(num, row, col): + for i in range(9): + if board[row][i] == num or board[i][col] == num: + return False + + start_row, start_col = 3 * (row // 3), 3 * (col // 3) + for i in range(3): + for j in range(3): + if board[start_row + i][start_col + j] == num: + return False + return True + + def backtrack(): + for row in range(9): + for col in range(9): + if board[row][col] == ".": + for num in map(str, range(1, 10)): + if is_valid(num, row, col): + board[row][col] = num + if backtrack(): + return True + board[row][col] = "." + return False + return True + + if not board or len(board) != 9 or len(board[0]) != 9: + return + + backtrack() + +# Example Sudoku puzzle as a 2D list, use "." for empty cells +sudoku_board = [ + ["5", "3", ".", ".", "7", ".", ".", ".", "."], + ["6", ".", ".", "1", "9", "5", ".", ".", "."], + [".", "9", "8", ".", ".", ".", ".", "6", "."], + ["8", ".", ".", ".", "6", ".", ".", ".", "3"], + ["4", ".", ".", "8", ".", "3", ".", ".", "1"], + ["7", ".", ".", ".", "2", ".", ".", ".", "6"], + [".", "6", ".", ".", ".", ".", "2", "8", "."], + [".", ".", ".", "4", "1", "9", ".", ".", "5"], + [".", ".", ".", ".", "8", ".", ".", "7", "9"] +] + +solve_sudoku(sudoku_board) + +# Print the solved Sudoku board +for row in sudoku_board: + print(" ".join(row))