N puzzle

 import heapq


def heuristic(state, goal):

    return sum(abs(s % 3 - g % 3) + abs(s // 3 - g // 3) for s, g in zip(state, goal) if s)


def get_neighbors(state):

    i = state.index(0)

    moves = [(i-3, i), (i+3, i), (i-1, i), (i+1, i)]

    neighbors = []

    for new, old in moves:

        if 0 <= new < 9 and not (i % 3 == 0 and old % 3 == 2) and not (i % 3 == 2 and old % 3 == 0):

            new_state = list(state)

            new_state[old], new_state[new] = new_state[new], new_state[old]

            neighbors.append(tuple(new_state))

    return neighbors


def a_star(start, goal):

    pq, visited = [(0 + heuristic(start, goal), 0, start)], set()

    while pq:

        _, cost, state = heapq.heappop(pq)

        if state in visited: continue

        visited.add(state)

        if state == goal: return cost

        for neighbor in get_neighbors(state):

            if neighbor not in visited:

                heapq.heappush(pq, (cost + 1 + heuristic(neighbor, goal), cost + 1, neighbor))


start = (1, 2, 3, 4, 5, 6, 7, 8, 0) # Example start state

goal = (1, 2, 3, 4, 5, 6, 7, 8, 0) # Example goal state

print(a_star(start, goal))

 N-Puzzle

Comments

Popular posts from this blog

Web

Lab 1 ai