|
def print_board(tablero): |
|
for i in range(len(tablero)): |
|
if i % 3 == 0 and i != 0: |
|
print("------+-------+------") |
|
|
|
for j in range(len(tablero[0])): |
|
if j % 3 == 0 and j != 0: |
|
print("| ", end="") |
|
|
|
if j == 8: |
|
print(tablero[i][j]) |
|
else: |
|
print(str(tablero[i][j]) + " ", end="") |
|
|
|
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): |
|
|
|
for i in range(len(tablero[0])): |
|
if tablero[pos[0]][i] == num and pos[1] != i: |
|
return False |
|
|
|
|
|
for i in range(len(tablero)): |
|
if tablero[i][pos[1]] == num and pos[0] != i: |
|
return False |
|
|
|
|
|
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) |
|
|
|
return None |
|
|
|
|
|
|
|
|
|
|
|
import gradio as gr |
|
|
|
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) |
|
|
|
demo = gr.Interface( |
|
fn=function, |
|
inputs=gr.Textbox(lines=2, label="Sudoku", placeholder="Ingrese la cadena del sudoku"), |
|
outputs=gr.Textbox(lines=10, label="Resultado", placeholder="Resultado..."), |
|
examples=[["780400120600075009000601078007040260001050930904060005070300012120007400049206007"]] |
|
) |
|
|
|
demo.launch(inline=False) |