File size: 2,289 Bytes
745f025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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):
    # 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 caja
    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

# ********************************************************************************
# INTERFAZ
# ********************************************************************************
    
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)