First of all we are here to tell us about prim algorithms, data structures, I remember the first university finished minimum spanning tree, tell the shortest path problem is a compulsory study section.
prim global minimum spanning tree algorithm to find weighting FIG communication inside. It is a greedy algorithm.
Here are two pictures I steal oh. Hee hee hee
algorithm:
1, input: a weighted FIG communication, set V of vertices, a set E of edges.
Input representation of a two-dimensional matrix (Note: there is no set length of a side of the communication MAX): as
Import SYS MAX = sys.maxsize # set to infinity
The matrix is expressed as:
primgraph = [[MAX, 6, 1, 5, MAX, MAX], [6, MAX, 5, MAX, 3, MAX], [1, 5, MAX, 5, 6, 4], [5, MAX, 5, MAX, MAX,2], [MAX, 3, 6, MAX, MAX, 6], [MAX, MAX, 4, 2, 6, MAX]] chararray = ['A', 'B', 'C', 'D', 'E', 'F']
Initialization value: The total cost of the minimum spanning tree --lowcost, open up an array of storage node minimum spanning tree
charlist.append (chararray [0]) # store a first initial node Lowcost = [] lowcost.append ( -1) # first storage node is set to 0
SUM is the total weight of the minimum spanning tree weight
Add the remaining inter initialization initialization point A lowcost
for i in range(1, n): lowcost.append(primgraph[0][i])
He began tentatively on the edge of victory
Start the next iteration
for _ in Range (. 1, n-): # traversing nodes other than the point A min = MAX # per find the smallest edge, min for comparing minid 0 = # per minid used to store the lowest node index for J in Range (. 1, n-): # find the minimum weight junction, and! = -1 is not favorite of the emperor IF Lowcost [J] = -1! And Lowcost [J] < min: min = Lowcost [J] minid = J charlist.append (chararray [minid]) # minimum spanning added shortest path that node SUM = SUM + min #Total weight plus the weight of the remaining nodes in the shortest weight Lowcost [minid] -1 = # of the node just been patronize the shortest path, past the formula for J in Range (. 1, n-): # update list favorite of the most critical part! ! ! ! IF Lowcost [J] = -1! and Lowcost [J]> primgraph [minid] [J]: # all nodes already patronize, patronize from the node has to find the shortest path, updated lowcost [j] = primgraph [ mini