Slitherlink Puzzle

84 Views Asked by At

I am tryin to solve the slitherlink_puzzle in python however, I am going into an infinite loop or missing something. I even tried using ChatGPT to help me with this but it was in vain. The rules are as follows : The dots need to be connected by continuous path, horizontally or vertically. The number between the dots indicate how many of its sides are part of the loop. The complete grid should be closed, with no loose ends or branches. (-1 represents empty cell) Attaching a YT video for better understanding of puzzle: https://www.youtube.com/watch?v=8Y078AkyZRQ

def solve_slitherlink_puzzle(board):
    n = len(board)
    solution = [[None] * (n + 1) for _ in range(n + 1)]

    def is_valid_move(row, col):
        return 0 <= row < n + 1 and 0 <= col < n + 1

    def is_loop_complete():
        for row in range(n):
            for col in range(n):
                if board[row][col] != -1:
                    count = 0
                    if solution[row][col] == "right":
                        count += 1
                    if solution[row + 1][col] == "left":
                        count += 1
                    if solution[row][col + 1] == "left":
                        count += 1
                    if solution[row + 1][col + 1] == "right":
                        count += 1

                    if count != board[row][col]:
                        return False
        return True

    def solve_recursive(row, col):
        if row == n + 1:
            return is_loop_complete()

        next_row = row if col < n else row + 1
        next_col = col + 1 if col < n else 0

        if is_valid_move(row, col):
            solution[row][col] = "right"
            solution[row + 1][col] = "left"
            if solve_recursive(next_row, next_col):
                return True

            solution[row][col] = "down"
            solution[row + 1][col] = "up"
            if solve_recursive(next_row, next_col):
                return True

            solution[row][col] = None
            solution[row + 1][col] = None

        return False

    if solve_recursive(0, 0):
        return solution
    else:
        return None


# Example puzzle
board = [
    [-1, 3, -1, 2, 0, -1, 3, -1, 1],
    [2, -1, 1, -1, -1, -1, 0, 2, -1],
    [-1, -1, -1, 2, 0, 2, 2, -1, -1],
    [3, 0, -1, 2, -1, -1, 2, -1, 3],
    [-1, -1, -1, 2, 3, 2, 1, -1, -1],
    [3, -1, 2, 1, -1, 1, -1, 1, -1],
    [-1, 3, -1, 2, -1, 1, 2, 2, -1],
    [-1, -1, 2, 2, -1, -1, 1, -1, -1],
    [-1, 2, -1, 2, 2, 2, -1, -1, -1]
]

solution = solve_slitherlink_puzzle(board)

if solution is not None:
    for row in solution:
        print(row)
else:
    print("No solution found.")
0

There are 0 best solutions below