예제 #1
0
def prim(first, graph):
    pQueue = PriorityQueue()
    graph[first]['dist'] = 0
    for i in graph:
        pQueue.enqueue((graph[i]['dist'], i))
    mst = []
    # dictionary to record for each vertex in the queue its nearest vertex in the tree
    nearestInTreeTo = {}
    print('Removing front item', first, 'from priority queue')
    while not pQueue.isEmpty():
        u = pQueue.dequeue()

        print('Inspecting neighbours of vertex', u)

        for w in graph[u]['edgeTo']:

            edgeLen = graph[u]['edgeTo'][w]
            print(u, 'to', w,':', edgeLen)

            currentDist = graph[w]['dist']
            if w in pQueue and edgeLen < currentDist:
                graph[w]['dist'] = edgeLen
                pQueue.changePriority(w, edgeLen)
                nearestInTreeTo[w] = u

        if not pQueue.isEmpty():

            print('PriorityQueue is now :', pQueue.getEntries())
            print()

            nextVertex = pQueue.peek()
            print('Next vertex is:', nextVertex)
            weight = graph[nextVertex]['dist']
            newEdge = [[(nearestInTreeTo[nextVertex], nextVertex), weight]]


            print('Nearest in tree to', nextVertex,'is', nearestInTreeTo[nextVertex])
            print('Adding', newEdge, 'to the tree')
            mst = mst + [[(nearestInTreeTo[nextVertex], nextVertex), weight]]

            print('Tree is now :', mst)
            print()
            print('Removing front item', nextVertex, 'from priority queue')

    print('MST completed')
    return mst