sudoku / app.py
rubend18's picture
Update app.py
692bff0
import gradio as gr
def print_board(tablero):
output = ""
for i in range(len(tablero)):
for j in range(len(tablero[0])):
if j == 8:
output += str(tablero[i][j]) + "\n"
else:
output += str(tablero[i][j]) + " "
return output
def resolver(tablero):
buscar = buscar_vacio(tablero)
if not buscar:
return True
else:
fila, columna = buscar
for i in range(1,10):
if es_valido(tablero, i, (fila, columna)):
tablero[fila][columna] = i
if resolver(tablero):
return True
tablero[fila][columna] = 0
return False
def es_valido(tablero, num, pos):
# Comprobar fila
for i in range(len(tablero[0])):
if tablero[pos[0]][i] == num and pos[1] != i:
return False
# Comprobar columna
for i in range(len(tablero)):
if tablero[i][pos[1]] == num and pos[0] != i:
return False
# Comprobar cuadrado
caja_x = pos[1] // 3
caja_y = pos[0] // 3
for i in range(caja_y*3, caja_y*3 + 3):
for j in range(caja_x * 3, caja_x*3 + 3):
if tablero[i][j] == num and (i,j) != pos:
return False
return True
def buscar_vacio(tablero):
for i in range(len(tablero)):
for j in range(len(tablero[0])):
if tablero[i][j] == 0:
return (i, j) # fila, columna
return None
def function(cadena):
tablero = []
for i in range(0, 81, 9):
row = [int(num) for num in cadena[i:i+9]]
tablero.append(row)
resolver(tablero)
return print_board(tablero)
value1 = gr.Textbox(lines=2, label="Sudoku", placeholder="Ingrese la cadena del sudoku")
value2 = gr.Textbox(lines=10, label="Solución", placeholder="Solución...")
examples=[
["400030000000600800000000001000050090080000600070200000000102700503000040900000000"],
["708000300000201000500000000040000026300080000000100090090600004000070500000000000"],
["708000300000601000500000000040000026300080000000100090090200004000070500000000000"],
["307040000000000091800000000400000700000160000000250000000000380090000500020600000"],
["500700600003800000000000200620400000000000091700000000000035080400000100000090000"],
["400700600003800000000000200620500000000000091700000000000043080500000100000090000"],
["040010200000009070010000000000430600800000050000200000705008000000600300900000000"],
["705000002000401000300000000010600400200050000000000090000370000080000600090000080"],
["000000410900300000300050000048007000000000062010000000600200005070000800000090000"],
["780400120600075009000601078007040260001050930904060005070300012120007400049206007"]]
demo = gr.Interface(
fn=function,
inputs=value1,
outputs=value2,
title="Resolver Sudoku",
examples=examples,
description="Resuelve un Sudoku a partir de una cadena"
)
demo.launch(debug=True)