Create a streamlit app that takes in the current configuration of a sudoku board (of a customizable size) and returns a solved version of it.
To upload files, please first save the app
import streamlit as st
import numpy as np
def solve_sudoku(board):
empty = find_empty(board)
if not empty:
return True # Solved
row, col = empty
for num in range(1, 10): # Numbers 1-9
if is_valid(board, num, row, col):
board[row][col] = num # Place number
if solve_sudoku(board):
return True
board[row][col] = 0 # Reset on backtrack
return False
def find_empty(board):
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] == 0:
return (r, c) # Row, Col
return None
def is_valid(board, num, row, col):
# Check row
if num in board[row]:
return False
# Check column
if num in [board[r][col] for r in range(len(board))]:
return False
# Check box
box_row_start = (row // 3) * 3
box_col_start = (col // 3) * 3
for r in range(box_row_start, box_row_start + 3):
for c in range(box_col_start, box_col_start + 3):
if board[r][c] == num:
return False
return True
st.title("Sudoku Solver")
size = st.sidebar.number_input("Select the size of the Sudoku (3 for 9x9)", min_value=1, max_value=3, value=1)
n = size * 3
board = np.zeros((n, n), dtype=int)
for i in range(n):
row = st.text_input(f"Row {i + 1} (comma separated)", "").split(',')
board[i] = [int(num) if num.strip() else 0 for num in row]
if st.button("Solve Sudoku"):
if solve_sudoku(board):
st.success("Solved Sudoku:")
st.table(board)
else:
st.error("No solution exists.")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?