Пример #1
0
class Dijkstra:
    def __init__(self):
       pass

    def dijkstra(self):

        self.initializeSingleSource()
        S = []                                            #a set of vertices whose final shortest path weights have already been determined

        Q = list(self.graph.vertexMap.values())                         #list of vertices

        self.heap = MinHeap(Q, key = lambda vertex : vertex.d)               #heap implementation using key as vertex.

        while len(self.heap) > 0:
        # while Q != None and len(Q) > 0:
        #     minDVertex = min(Q, key= lambda  v: v.d)                    #If using basic list, which uses O(n) as the running time.
        #     Q.remove(minDVertex)

            minDVertex = self.heap.extractMin()

            if not minDVertex.status :
                continue                                                #skipping the vertices which are down.

            S.append(minDVertex)
            for edge in minDVertex.adj:                                 #retrieving edges
                # print("adjcnt item is ", edge.destination.name)
                if not edge.status or not edge.destination.status:
                    continue                                            #skipping the edges which are down.
                nextVertex = edge.destination           #retrieving destination vertex from edge data
                transit_time = edge.transit_time
                self.Relax(minDVertex, nextVertex, transit_time)

        return self.source, self.destination



    def Relax(self, minDVertex, nextVertex, transit_time):
        newValue = minDVertex.d + transit_time
        if nextVertex.d > newValue:
            # nextVertex.d = minDVertex.d + transit_time
            self.heap.heapDecreaseKey(nextVertex, newValue, nextVertex.setKeyForHeap)
            nextVertex.pi = minDVertex

    def initializeSingleSource(self):                       #O(V)
        for vertex in self.graph.vertexMap.values():
            vertex.d = sys.maxsize
            vertex.pi = None
        self.source.d = 0

    def minPath(self, graph, source, destination):
        self.graph = graph
        self.destination = graph.vertexMap[destination]
        self.source = graph.vertexMap[source]               #O(1)
        return self.dijkstra()
Пример #2
0
    def dijkstra(self):

        self.initializeSingleSource()
        S = []                                            #a set of vertices whose final shortest path weights have already been determined

        Q = list(self.graph.vertexMap.values())                         #list of vertices

        self.heap = MinHeap(Q, key = lambda vertex : vertex.d)               #heap implementation using key as vertex.

        while len(self.heap) > 0:
        # while Q != None and len(Q) > 0:
        #     minDVertex = min(Q, key= lambda  v: v.d)                    #If using basic list, which uses O(n) as the running time.
        #     Q.remove(minDVertex)

            minDVertex = self.heap.extractMin()

            if not minDVertex.status :
                continue                                                #skipping the vertices which are down.

            S.append(minDVertex)
            for edge in minDVertex.adj:                                 #retrieving edges
                # print("adjcnt item is ", edge.destination.name)
                if not edge.status or not edge.destination.status:
                    continue                                            #skipping the edges which are down.
                nextVertex = edge.destination           #retrieving destination vertex from edge data
                transit_time = edge.transit_time
                self.Relax(minDVertex, nextVertex, transit_time)

        return self.source, self.destination
Пример #3
0
def heap_sort(heap_list):
    h = MinHeap.MinHeap()

    i = len(heap_list) // 2 - 1
    while i >= 0:
        h.percolate_down(i, heap_list, len(heap_list))
        i = i - 1

    i = len(heap_list) - 1
    while i > 0:
        # swap
        temp = heap_list[0]
        heap_list[0] = heap_list[i]
        heap_list[i] = temp

        h.percolate_down(0, heap_list, i)
        i = i - 1
Пример #4
0
def getMaxProfit(costs, profits, c, k):
    if len(costs) != len(profits):
        return 0
    data = []
    for i in range(len(costs)):
        node = Node(costs[i], profits[i])
        data.append(node)
    costMinHeap = MinHeap.MinHeap()
    for d in data:
        costMinHeap.push(d)
    profitsMaxHeap = PriorityQueue.PriorityQueue()
    for index in range(k):
        while not costMinHeap.isEmpty() and costMinHeap.peek().cost <= c:
            n = costMinHeap.pop()
            profitsMaxHeap.push(n, n.profit)
        if profitsMaxHeap.isEmpty():
            break
        item = profitsMaxHeap.pop()
        c += item[1].profit
    return c
Пример #5
0
 def dijkstra(self, source_label):
     for vertex in self.vertices:
         vertex.distance = self.inf
         vertex.predecessor = None
     source_vertex = self.vertices[source_label]
     source_vertex.distance = 0
     priority_queue = MinHeap(self.vertices[:])
     while not priority_queue.empty():
         w = priority_queue.extract_min()
         for v_label in self.adjacency_list[w.label]:
             v = self.vertices[v_label]
             dwv = self.edge_weight[self.edge(w.label, v.label)]
             if v.distance == self.inf or w.distance + dwv < v.distance:
                 v.distance = w.distance + dwv
                 v.predecessor = w
                 priority_queue.update_priority(v.index)
 def __init__(self):
     self.maxh = MaxHeap.MaxHeap()
     self.minh = MinHeap.MinHeap()
     self.medians = list()
Пример #7
0
x = np.zeros((n_random_pts, n_dim), dtype=np.float);
y = np.zeros((total_docs, n_dim), dtype=np.float);

ind_fp = open('topic_indexes1.txt' , 'r')
random_pts = [];
for line in ind_fp:
    index = long(line) - 1;
    random_pts.append(index);
    random_pts.sort();

output = np.zeros((n_random_pts, k_nearest + 1) , dtype = np.long);
min_heaps = [];

for i in xrange(n_random_pts):
    output[i][0] = random_pts[i];
    min_heaps.append(mh.MinHeap());

t_i = 0
f_i = 0;
total_iterations = 20;
one_cycle_iterations = 4;

rand_i = 0;
while t_i < total_iterations:
    i = 0;
    f_i = 0;
    while f_i < one_cycle_iterations:
        try:
            doc = pickle.load(in_fp);
            n_iter += 1;
            n_doc = len(doc);
Пример #8
0
# import heap class
from 03-min_heap import MinHeap 

min_heap = MinHeap()
print(min_heap.heap_list)

# testing out .add()
min_heap.add(42)
print(min_heap.heap_list)
Пример #9
0

import MinHeap

heap = MinHeap.Heap()

heap.insert(3)
Пример #10
0
def main():
    """Main method, does some testing."""
    print( "*** Initializing new MinHeap ... done." )
    print( "*** Adding values 7, 42, 999, 0, 212, 512, 21 ... done." )

    test = MinHeap()

    test.insert( 7   )
    test.insert( 42  )
    test.insert( 999 )
    test.insert( 0   )
    test.insert( 212 )
    test.insert( 512 )
    test.insert( 21  )

    print( "   ### Current MinHeap: " )
    test.println()
    print( "\n   ### Number of Nodes: " + str( test.getSize() ))

    print( "\n*** Performing \"deleteMin\" ... done." )
    test.deleteMin()

    print( "   ### Current MinHeap: " )
    test.println()
    print( "\n   ### Number of Nodes: " + str( test.getSize() ))
Пример #11
0
 def __init__(self):
     self.maxHeap = MaxHeap.MaxHeap()
     self.minHeap = MinHeap.MinHeap()
Пример #12
0
from MinHeap import *

l = [10, 45, 21, 44, 22, 14, 20, 40, 100, 32, 56, 12, 54]
min_heap1 = MinHeap()
for element in l:
    min_heap1.insert(element)
ssl = sorted(l)
sl1 = []
while min_heap1.minimum() is not None:
    sl1.append(min_heap1.extract_min())
print(ssl)
print(sl1)
min_heap2 = MinHeap(l)
sl2 = []
while min_heap2.minimum() is not None:
    sl2.append(min_heap2.extract_min())
print(sl2)
Пример #13
0
import MaxHeap
import MinHeap

min_heap = []
max_heap = []

current_median = 0.0

stream = [6, 1, 5, 2, 4, 3, 1, 7, 7, 8]

for value in stream:
    if current_median > value:
        MaxHeap.push_heap(max_heap, value)
    else:
        MinHeap.push_heap(min_heap, value)

    current_median = value

    if len(max_heap)-len(min_heap) > 1:
        max_value = MaxHeap.pop_heap(max_heap)
        MaxHeap.push_heap(min_heap, max_value)
    elif len(min_heap)-len(max_heap) > 1:
        min_value = MinHeap.pop_heap(min_heap)
        MinHeap.push_heap(max_heap, min_value)

    if len(max_heap) == len(min_heap):
        current_median = (max_heap[0]+min_heap[0])/2
    elif len(max_heap) > len(min_heap):
        current_median = max_heap[0]
    else:
        current_median = min_heap[0]
Пример #14
0
 def min_in_heap(self, notExplored, distance):
     minHeap = MinHeap.MinHeap(distance.values())
     minimumDist = minHeap.getAndDeleteMinimum()
     for i in notExplored:
         if distance[i] == minimumDist:
             return i
Пример #15
0
    def dijkstra(self, start, dest, time):
        self.timeM.managingTime(time)
        nodes = dict(self.graph).keys()
        distance = {}
        previous = {}
        distanceDetails = {}

        for i in dict(self.graph).keys():
            distance[i] = float("inf")
            previous[i] = None

        distance[start] = 0

        notExplored = set(nodes)
        minHeap = MinHeap.MinHeap(notExplored)
        while len(notExplored) > 0:

            current_Node = self.min_in_heap(notExplored, distance)

            currentNode = self.minimum_distance(distance, notExplored)
            if (currentNode == 0):
                break
            notExplored.remove(currentNode)

            if distance[currentNode] == float('inf'):
                break

            neighborhood = (dict(self.graph)[currentNode])[1]
            for vertex in neighborhood:
                #
                self.timeM.graphRestarter()

                # for i in dict(self.graph).keys():
                #     print(i, "  :::  ", self.graph[i])
                self.timeM.managingTime(distance[currentNode] + time)
                wheight = distance[currentNode] + (self.dist_between(currentNode, vertex) * (1 + (0.3 * vertex[1])))

                if wheight < distance[vertex[0]]:
                    distance[vertex[0]] = wheight
                    previous[vertex[0]] = currentNode
        destCP = dest
        print(" ")
        while True:
            print(destCP, end=" <- ")

            try:
                previous[destCP]
                # self.traffic_handler(destCP, previous[destCP])



            except KeyError:
                break

            destCP = previous[destCP]
        print(" ")
        # for i in distance.keys():
        #     print(i," : ",distance[i]*120)

        self.prvus = previous
        self.dstnc = distance
        #
        self.timeM.newRequest(distance, previous, dest, time)
        return previous
# import heap class
from 02-min_heap import MinHeap 

# Make an instance of MinHeap
heap = MinHeap()

# Print out the internal list
print(heap.heap_list)
    print(tree[index])
    preOrderTraversal(tree, (2 * index + 1))
    preOrderTraversal(tree, (2 * index + 2))


def postOrderTraversal(tree, index):
    if index > len(tree) - 1:
        return

    # Left, right, Root
    preOrderTraversal(tree, (2 * index + 1))
    preOrderTraversal(tree, (2 * index + 2))
    print(tree[index])


print("In-Order Traversal")
inOrderTraversal(tree, 0)

print("Pre-Order Traversal")
preOrderTraversal(tree, 0)

print("Post-Order Traversal")
postOrderTraversal(tree, 0)

# lets test the heap stuff that we just made
heap = MinHeap.MinHeap()
for x in range(20):
    heap.insert(random.randint(0, 100))

print("Current Min Heap: {}".format(heap.heap))
Пример #18
0
# importing heap class
from 04-min_heap import MinHeap 

# an instance of MinHeap to use
min_heap = MinHeap()

# the internal list for our example
min_heap.heap_list = [None, 10, 13, 21, 61, 22, 23, 99]
print(min_heap.heap_list)


# example of how to use the helper methods:
print("the parent index of 4 is:")
print(min_heap.parent_idx(4))
print("the left child index of 3 is:")
print(min_heap.left_child_idx(3))

# now it's your turn!
# replace 'None' below using the correct helper methods and indexes
idx_2_left_child_idx = min_heap.left_child_idx(2)
print("The left child index of index 2 is:")
print(idx_2_left_child_idx)
print("The left child element of index 2 is:")
# uncomment the line below to see the result in your console!
print(min_heap.heap_list[idx_2_left_child_idx])

idx_3_parent_idx = min_heap.parent_idx(3)
print("The parent index of index 3 is:")
print(idx_3_parent_idx)
print("The parent element of index 3 is:")
# uncomment the line below to see the result in your console!
# import random number generator
from random import randrange
# import heap class
from 05-min_heap import MinHeap 

# make an instance of MinHeap
min_heap = MinHeap()

# populate min_heap with random numbers
random_nums = [randrange(1, 101) for n in range(6)]
for el in random_nums:
  min_heap.add(el)


# test it out, is the minimum number at index 1?
print(min_heap.heap_list)
Пример #20
0
def probPartialHaplotype(partialSolution, sortedArraybySkewness,
                         dictColumnPosition):

    dictpreComputation = defaultdict(list)
    my_dicts1 = dict()
    objtoPair = {}  # store pair to its objective function

    finalSolution = []
    heap = MinHeap.MinHeap()
    initialise = 0

    index = 0
    for row in sortedArraybySkewness[:, -len(
            partialSolution
    ):]:  # Precomputation of probability given partial Solution
        dictpreComputation[index] = [
            probPair(partialSolution, row, 0),
            probPair(partialSolution, row, 1)
        ]
        index = index + 1

    optimalSolution = [[partialSolution, partialSolution]]
    my_dicts1["dict" + str(partialSolution)] = dictpreComputation

    for coloumnIndex in range(-(1 + len(partialSolution)),
                              -sortedArraybySkewness.shape[1] - 1,
                              -1):  #ignore last coloumn

        tempArray = sortedArraybySkewness[:, coloumnIndex]

        my_dicts = my_dicts1
        my_dicts1 = {}

        if initialise == 1:
            optimalSolution = []
            for key, pair in objtoPair.items():
                optimalSolution.append(pair)
            heap = MinHeap.MinHeap()
            objtoPair = {}

        for element1, element2 in optimalSolution:

            dictpreComputationelm1 = my_dicts["dict" + str(element1)]
            dictpreComputationelm2 = my_dicts["dict" + str(element2)]
            dictpreComputation10 = defaultdict(list)
            dictpreComputation11 = defaultdict(list)
            dictpreComputation20 = defaultdict(list)
            dictpreComputation21 = defaultdict(list)

            for rownumber in range(tempArray.shape[0]):
                if tempArray[rownumber] == 0:
                    dictpreComputation10[rownumber] = [
                        F00l1 * dictpreComputationelm1[rownumber][0],
                        F00l2 * dictpreComputationelm1[rownumber][1]
                    ]
                    dictpreComputation11[rownumber] = [
                        F01l1 * dictpreComputationelm1[rownumber][0],
                        F01l2 * dictpreComputationelm1[rownumber][1]
                    ]
                    dictpreComputation20[rownumber] = [
                        F00l1 * dictpreComputationelm2[rownumber][0],
                        F00l2 * dictpreComputationelm2[rownumber][1]
                    ]
                    dictpreComputation21[rownumber] = [
                        F01l1 * dictpreComputationelm2[rownumber][0],
                        F01l2 * dictpreComputationelm2[rownumber][1]
                    ]

                else:
                    dictpreComputation10[rownumber] = [
                        F01l1 * dictpreComputationelm1[rownumber][0],
                        F01l2 * dictpreComputationelm1[rownumber][1]
                    ]
                    dictpreComputation11[rownumber] = [
                        F00l1 * dictpreComputationelm1[rownumber][0],
                        F00l2 * dictpreComputationelm1[rownumber][1]
                    ]
                    dictpreComputation20[rownumber] = [
                        F01l1 * dictpreComputationelm2[rownumber][0],
                        F01l2 * dictpreComputationelm2[rownumber][1]
                    ]
                    dictpreComputation21[rownumber] = [
                        F00l1 * dictpreComputationelm2[rownumber][0],
                        F00l2 * dictpreComputationelm2[rownumber][1]
                    ]

            tempProb10 = sum(
                sum(summ) for summ in dictpreComputation10.values())
            tempProb11 = sum(
                sum(summ) for summ in dictpreComputation11.values())
            tempProb20 = sum(
                sum(summ) for summ in dictpreComputation20.values())
            tempProb21 = sum(
                sum(summ) for summ in dictpreComputation21.values())

            solutionspace = []
            if tempProb10 > tempProb11:
                solutionspace.append([[0] + element1, [1] + element2])

            else:
                solutionspace.append([[1] + element1, [0] + element2])

            if tempProb20 > tempProb21 and tempProb10 > tempProb11:
                solutionspace.append([[1] + element1, [0] + element2])

            elif tempProb20 < tempProb21 and tempProb10 < tempProb11:
                solutionspace.append([[0] + element1, [1] + element2])

            for inferhap11, inferhap22 in solutionspace:

                if inferhap11 == [0] + element1 and inferhap22 == [
                        1
                ] + element2:
                    dictpreComputation0 = dictpreComputation10
                    dictpreComputation1 = dictpreComputation21
                    objectValue = objective(tempProb10, tempProb21)

                elif inferhap11 == [1] + element1 and inferhap22 == [
                        0
                ] + element2:
                    dictpreComputation0 = dictpreComputation11
                    dictpreComputation1 = dictpreComputation20
                    objectValue = objective(tempProb11, tempProb20)

                if heap.currentSize < 20:

                    heap.insert(objectValue)
                    objtoPair[objectValue] = [inferhap11, inferhap22]
                    my_dicts1["dict" + str(inferhap11)] = dictpreComputation0
                    my_dicts1["dict" + str(inferhap22)] = dictpreComputation1

                else:
                    if objectValue < heap.heapList[
                            1]:  #mininmum value check condition
                        continue
                    else:
                        minpop = heap.delMin()  #Remove mininmum from heap
                        objtoPair.pop(minpop,
                                      None)  #Remove minimum from dictionary

                        heap.insert(objectValue)
                        objtoPair[objectValue] = [inferhap11, inferhap22]
                        my_dicts1["dict" +
                                  str(inferhap11)] = dictpreComputation0
                        my_dicts1["dict" +
                                  str(inferhap22)] = dictpreComputation1

            if initialise == 0:
                initialise = 1

    try:
        pairSolution = objtoPair[max(heap.heapList)]

    except KeyError:
        print 'Key Error'
        return sortedArraybySkewness[1, ]

    try:
        partialSolution = pairSolution[1]

    except UnboundLocalError:
        print 'Unbound Local Error'
        return sortedArraybySkewness[1, ]

    for key, value in sorted(dictColumnPosition.iteritems(),
                             key=lambda (k, v): (v, k)):
        finalSolution.append(int(partialSolution[key]))
    return finalSolution
Пример #21
0
def main():
    # __________TEST 1__________________________________________________________________________________________________
    print('\n__________TEST 1__________: Uses file with 1,000 numbers.')
    # Creates list from file. This is the test we will be using.
    input_list = MinHeap.file_to_list("Numbers.txt")
    print('List before converting to min heap:\n', input_list)

    start_time = time.time()

    # Builds min heap from list then prints list.
    min_heap = MinHeap.build_min_heap(input_list)
    print('After converting to min heap:\n', min_heap.heap_array)

    # Sorts min heap using heap sort then prints list once sorted.
    heap_sort(min_heap.heap_array)
    print('After using heap sort:\n', min_heap.heap_array)

    print(
        "\nRunning time after building min heap then sorting it = %s seconds" %
        (time.time() - start_time))

    # __________TEST 2__________________________________________________________________________________________________
    print('\n__________TEST 2__________: Uses hard coded list.')
    # Creates list from file. This is the test we will be using.
    input_list = [12, 4567, 2, 4, 1, 5678, 34, 43, 6, 7]
    print('List before converting to min heap:\n', input_list)

    start_time = time.time()

    # Builds min heap from list then prints list.
    min_heap = MinHeap.build_min_heap(input_list)
    print('After converting to min heap:\n', min_heap.heap_array)

    # Sorts min heap using heap sort then prints list once sorted.
    heap_sort(min_heap.heap_array)
    print('After using heap sort:\n', min_heap.heap_array)

    print(
        "\nRunning time after building min heap then sorting it = %s seconds" %
        (time.time() - start_time))

    # __________TEST 3__________________________________________________________________________________________________
    print('\n__________TEST 3__________: Uses empty file.')
    # Creates list from file. This is the test we will be using.
    input_list = MinHeap.file_to_list("Empty.txt")
    print('List before converting to min heap:\n', input_list)

    start_time = time.time()

    # Builds min heap from list then prints list.
    min_heap = MinHeap.build_min_heap(input_list)
    print('After converting to min heap:\n', min_heap.heap_array)

    # Sorts min heap using heap sort then prints list once sorted.
    heap_sort(min_heap.heap_array)
    print('After using heap sort:\n', min_heap.heap_array)

    print(
        "\nRunning time after building min heap then sorting it = %s seconds" %
        (time.time() - start_time))

    # __________TEST 4__________________________________________________________________________________________________
    print('\n__________TEST 4__________: Uses file not formatted.')
    # Creates list from file. This is the test we will be using.
    input_list = MinHeap.file_to_list("Not Formatted.txt")
    print('List before converting to min heap:\n', input_list)

    start_time = time.time()

    # Builds min heap from list then prints list.
    min_heap = MinHeap.build_min_heap(input_list)
    print('After converting to min heap:\n', min_heap.heap_array)

    # Sorts min heap using heap sort then prints list once sorted.
    heap_sort(min_heap.heap_array)
    print('After using heap sort:\n', min_heap.heap_array)

    print(
        "\nRunning time after building min heap then sorting it = %s seconds" %
        (time.time() - start_time))

    # __________TEST 5__________________________________________________________________________________________________
    print('\n__________TEST 5__________: Uses file that doesn\'t exist.')
    # Creates list from file. This is the test we will be using.
    input_list = MinHeap.file_to_list("Does Not Exist.txt")
    print('List before converting to min heap:\n', input_list)

    start_time = time.time()

    # Builds min heap from list then prints list.
    min_heap = MinHeap.build_min_heap(input_list)
    print('After converting to min heap:\n', min_heap.heap_array)

    # Sorts min heap using heap sort then prints list once sorted.
    heap_sort(min_heap.heap_array)
    print('After using heap sort:\n', min_heap.heap_array)

    print(
        "\nRunning time after building min heap then sorting it = %s seconds" %
        (time.time() - start_time))
Пример #22
0
# import random number generator
from random import randrange
# import heap class
from 10-min_heap import MinHeap 

# make an instance of MinHeap
min_heap = MinHeap()

# populate min_heap with descending numbers
descending_nums = [n for n in range(10001, 1, -1)]
print("ADDING!")
for el in descending_nums:
  min_heap.add(el)

print("REMOVING!")
# remove minimum until min_heap is empty
min_heap.retrieve_min()
# import random number generator
from random import randrange
# import heap class
from 08-min_heap import MinHeap 

# make an instance of MinHeap
min_heap = MinHeap()

# set internal list for testing purposes...
min_heap.heap_list = [None, 10, 13, 21, 61, 22, 23, 99]
min_heap.count = 7

print("The smaller child of index 1 is: ")
smaller_child_of_idx_1 = min_heap.get_smaller_child_idx(1)
smaller_child_element = min_heap.heap_list[smaller_child_of_idx_1]
print(smaller_child_element)

print("The smaller child of index 2 is: ")
smaller_child_of_idx_2 = min_heap.get_smaller_child_idx(2)
smaller_child_element = min_heap.heap_list[smaller_child_of_idx_2]
print(smaller_child_element)

print("The smaller child of index 3 is: ")
smaller_child_of_idx_3 = min_heap.get_smaller_child_idx(3)
smaller_child_element = min_heap.heap_list[smaller_child_of_idx_3]
print(smaller_child_element)
Пример #24
0
class Dijkstra:
    def __init__(self):
        self.heap = None  # 最小堆
        self.graph = None  # 图信息
        self.destination = None  # 目标定点
        self.source = None  # 源点
        pass

    def dijkstra(self):

        self.initializeSingleSource()
        S = []  #存储已求得最小值的顶点信息
        Q = list(self.graph.vertexMap.values())  #存储所有顶点
        self.heap = MinHeap(Q, key=lambda vertex: vertex.d)  #最小堆初始化

        while len(self.heap) > 0:
            minDVertex = self.heap.extractMin()
            if not minDVertex.status:
                continue  # 通过顶点状态过滤
            S.append(minDVertex)
            for edge in minDVertex.adj:  # 检索邻接点,结合最小堆进行松弛过程
                # print("adjacent item is ", edge.destination.name)
                if not edge.status or not edge.destination.status:
                    continue  # 跳过已经找到最短路径的点
                nextVertex = edge.destination  # 通过边获取终点
                weight = edge.weight
                self.Relax(minDVertex, nextVertex, weight)  # 松弛过程

    #为已经计算的最短路径进行松弛,更新最短路径
    def Relax(self, minDVertex, nextVertex, weight):
        newValue = minDVertex.d + weight
        if nextVertex.d > newValue:
            # nextVertex.d = minDVertex.d + weight
            self.heap.heapDecreaseKey(nextVertex, newValue,
                                      nextVertex.setKeyForHeap)
            nextVertex.pi = minDVertex

    #初始化
    def initializeSingleSource(self):
        for vertex in self.graph.vertexMap.values():
            vertex.d = sys.maxsize
            vertex.pi = None
        self.source.d = 0

    def minPath(self, graph, source, destination, return_list=True):
        self.graph = graph
        self.destination = graph.vertexMap[destination]
        self.source = graph.vertexMap[source]

        if return_list:
            path = []

            #遍历节点pi信息,获取最短路径数组
            def traverse(source_inner, destination_inner):
                if destination_inner == source_inner:
                    path.append(destination_inner.name)
                elif destination_inner.pi is None:
                    return
                else:
                    #递归
                    traverse(source_inner, destination_inner.pi)
                    path.append(destination_inner.name)

            self.dijkstra()
            traverse(self.source, self.destination)
            return path, self.destination.d
        else:
            return self.dijkstra()
Пример #25
0
def buildMinHeap(a):
    myHeap = MinHeap.MinHeap()
    for i in a:
        myHeap.insertNode(i)
    return myHeap