Untitled

 avatar
unknown
python
3 years ago
775 B
1
Indexable
import queue as Q

graph = {
    "P": {'Q': 1, 'R': 4},
    "Q": {'T': 12, 'S': 5, 'R': 2},
    "R": {'S': 2},
    "S": {'T': 3},
    "T": {}
}
start = 'P'
end = 'T'

if start not in graph or end not in graph:
    print('Please check start and end node in graph !')
else:
    queue = Q.PriorityQueue()
    queue.put((0, [start]))

    while not queue.empty():
        node = queue.get()
        current = node[1][len(node[1]) - 1]
        if end in node[1]:
            print("Path found: " + str(node[1]) + ", Cost = " + str(node[0]))
            break

        cost = node[0]
        for neighbor in graph[current]:
            temp = node[1][:]
            temp.append(neighbor)
            queue.put((cost + graph[current][neighbor], temp))
Editor is loading...