def dijkstra(source, graph):
    pQueue = PriorityQueue()
    graph[source]['dist'] = 0
    for v in graph:
        pQueue.enqueue((graph[v]['dist'], v))
    while not pQueue.isEmpty():
        u = pQueue.dequeue()
        baseDist = graph[u]['dist']
        print('Visiting',u, 'at distance', baseDist)
        print('Edges from this vertex', graph[u]['edgeTo'])
        for w in graph[u]['edgeTo']:
            edgeLen = graph[u]['edgeTo'][w]
            newDist = baseDist + edgeLen
            currentDist = graph[w]['dist']
            if newDist < currentDist:
                graph[w]['dist'] = newDist
                print('Distance to', w, 'set to', baseDist, '+', edgeLen, '=', newDist)
                pQueue.changePriority(w, newDist)
        print()
    # Print the results
    print('Final result: distances of all vertices from ' + source)
    distancesList = []
    for v in graph:
        distancesList.append((v, graph[v]['dist']))
    print(distancesList)
예제 #2
0
def bestFirstSearch(aTree):
    pQueue = PriorityQueue()
    pQueue.enqueue((aTree.getRoot().getPayload(), aTree.getRoot()))
    while not pQueue.isEmpty():
        printPriorityQueue(pQueue)
        nextNode = pQueue.dequeue()
        print('Visiting: ',
              nextNode.getKey(),
              '(',
              nextNode.getPayload(),
              ')',
              sep='')
        children = nextNode.getChildren()
        for child in children:
            pQueue.enqueue((child.getPayload(), child))
    printPriorityQueue(pQueue)
예제 #3
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
예제 #4
0
        bestFirstSearchRecursive(pQueue)


#Helper function for bestFirstSearch() and bestFirstSearchRecursive()
def printPriorityQueue(aPQueue):
    aList = aPQueue.getEntries()
    print('pQueue: [', end='')
    if not aPQueue.isEmpty():
        for item in aList[:-1]:
            print(item[1].getKey(), '(', item[0], '), ', sep='', end='')
        lastItem = aList[len(aList) - 1]
        print(lastItem[1].getKey(), '(', lastItem[0], ')', sep='', end='')
    print(']')
    print()


#Test the functions

print('------Testing breadthFirstSearch()------')
breadthFirstSearch(gameTree)
print()

print('------Testing bestFirstSearch()------')
bestFirstSearch(gameTree)
print()

print('------Testing bestFirstSearchRecursive()------')
thePQueue = PriorityQueue()
thePQueue.enqueue((gameTree.getRoot().getPayload(), gameTree.getRoot()))
bestFirstSearchRecursive(thePQueue)