corrige este codigo para que funcione perfectamente y encuentre rapido la solucion correcta: ""import tkinter as tk
from tkinter import messagebox
from random import choice, shuffle

# Definimos las piezas y sus conexiones
pieces = {
    'line': {
        'chars': ['─', '│', '─', '│'],
        'connections': [
            [0, 1, 0, 1],  # 0°
            [1, 0, 1, 0],  # 90°
            [0, 1, 0, 1],  # 180°
            [1, 0, 1, 0]   # 270°
        ]
    },
    'curve': {
        'chars': ['└', '┌', '┐', '┘'],
        'connections': [
            [1, 1, 0, 0],  # 0°
            [0, 1, 1, 0],  # 90°
            [0, 0, 1, 1],  # 180°
            [1, 0, 0, 1]   # 270°
        ]
    },
    't': {
        'chars': ['┬', '┤', '┴', '├'],
        'connections': [
            [0, 1, 1, 1],  # 0°
            [1, 0, 1, 1],  # 90°
            [1, 1, 0, 1],  # 180°
            [1, 1, 1, 0]   # 270°
        ]
    },
    'cross': {
        'chars': ['┼', '┼', '┼', '┼'],
        'connections': [
            [1, 1, 1, 1],  # Todas las rotaciones son iguales
            [1, 1, 1, 1],
            [1, 1, 1, 1],
            [1, 1, 1, 1]
        ]
    }
}

class Tile:
    def __init__(self, master, x, y, piece_type):
        self.master = master
        self.x = x
        self.y = y
        self.piece_type = piece_type
        self.rotation = 0  # Valores posibles: 0, 1, 2, 3 (equivalentes a 0°, 90°, 180°, 270°)
        self.button = tk.Button(master, text='', width=4, height=2, command=self.rotate)
        self.button.grid(row=y, column=x)
        self.update_connections()
    
    def rotate(self):
        self.rotation = (self.rotation + 1) % 4
        self.update_connections()
    
    def set_rotation(self, rotation):
        self.rotation = rotation % 4
        self.update_connections()
    
    def update_connections(self):
        # Actualizar conexiones y texto del botón según la rotación actual
        self.connections = pieces[self.piece_type]['connections'][self.rotation]
        self.button.config(text=pieces[self.piece_type]['chars'][self.rotation])

class PipePuzzle:
    def __init__(self, master, size):
        self.master = master
        self.size = size
        self.tiles = []
        self.create_board()
        self.start = (0, 0)
        self.end = (size - 1, size - 1)
        
        # Marcar el inicio y el fin
        self.tiles[self.start[1]][self.start[0]].button.config(bg='green')
        self.tiles[self.end[1]][self.end[0]].button.config(bg='red')
        
        # Botón para verificar solución
        self.check_button = tk.Button(master, text="Verificar Solución", command=self.check_solution)
        self.check_button.grid(row=size, column=0, columnspan=size//2)
        
        # Botón para resolver el puzzle
        self.solve_button = tk.Button(master, text="Resolver Puzzle", command=self.solve_puzzle)
        self.solve_button.grid(row=size, column=size//2, columnspan=size - size//2)
    
    def create_board(self):
        self.size = 5
        self.tiles = [[None for _ in range(self.size)] for _ in range(self.size)]
        piece_types = list(pieces.keys())
    
    # Generar un camino desde el inicio hasta el fin
        path = self.generate_path(self.start, self.end)
    
        for y in range(self.size):
            for x in range(self.size):
                if (x, y) in path:
                    piece_type, rotation = path[(x, y)]
                else:
                    piece_type = choice(piece_types)
                    rotation = choice([0, 1, 2, 3])
                tile = Tile(self.master, x, y, piece_type)
                tile.set_rotation(rotation)
                self.tiles[y][x] = tile
    
    def check_solution(self):
        visited = [[False]*self.size for _ in range(self.size)]
        if self.dfs(self.start[0], self.start[1], visited):
            messagebox.showinfo("Pipe Puzzle", "¡Has completado el circuito correctamente!")
        else:
            messagebox.showwarning("Pipe Puzzle", "El circuito no está correctamente conectado.")
    
    def dfs(self, x, y, visited):
        if (x, y) == self.end:
            return True
        visited[y][x] = True
        tile = self.tiles[y][x]
        dx = [0, 1, 0, -1]
        dy = [-1, 0, 1, 0]

        for i in range(4):
            if tile.connections[i]:
                nx, ny = x + dx[i], y + dy[i]
                if 0 <= nx < self.size and 0 <= ny < self.size:
                    neighbor = self.tiles[ny][nx]
                    opposite_direction = (i + 2) % 4
                    if neighbor.connections[opposite_direction] and not visited[ny][nx]:
                        if self.dfs(nx, ny, visited):
                            return True
        return False

    def solve_puzzle(self):
        self.disable_buttons()
        solution_found = self.backtracking_solve()
        if solution_found:
            self.animate_solution()
        else:
            messagebox.showwarning("Pipe Puzzle", "No se encontró una solución.")
            self.enable_buttons()

    def backtracking_solve(self):
        self.solution_steps = []
        visited = [[False]*self.size for _ in range(self.size)]
        return self.backtrack(0, 0, visited)

    def backtrack(self, x, y, visited):
        if (x, y) == self.end:
            return self.check_connections()
        if x >= self.size:
            x = 0
            y += 1
            if y >= self.size:
                return False
        tile = self.tiles[y][x]
        original_rotation = tile.rotation
        for rot in range(4):
            tile.set_rotation(rot)
            visited_copy = [row[:] for row in visited]
            if self.backtrack(x + 1, y, visited_copy):
                self.solution_steps.append((tile, rot))
                return True
        tile.set_rotation(original_rotation)
        return False

    def check_connections(self):
        visited = [[False]*self.size for _ in range(self.size)]
        return self.dfs(self.start[0], self.start[1], visited)

    def animate_solution(self):
        self.steps = self.solution_steps[::-1]
        self.animate_step()
    
    def animate_step(self):
        if self.steps:
            tile, rotation = self.steps.pop(0)
            tile.set_rotation(rotation)
            self.master.after(100, self.animate_step)
        else:
            messagebox.showinfo("Pipe Puzzle", "¡El puzzle ha sido resuelto!")
            self.enable_buttons()

    def disable_buttons(self):
        for row in self.tiles:
            for tile in row:
                tile.button.config(state='disabled')
        self.check_button.config(state='disabled')
        self.solve_button.config(state='disabled')

    def enable_buttons(self):
        for row in self.tiles:
            for tile in row:
                tile.button.config(state='normal')
        self.check_button.config(state='normal')
        self.solve_button.config(state='normal')

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Pipe Puzzle")
    game = PipePuzzle(root, size=5)
    root.mainloop()""