[arcpy learning practice tutorial] generate the minimum tree by using krusal minimum tree method

Keywords: Python

[requirement] generate the shortest path generated by pairwise to the minimum tree

[analysis] write a program according to the principle of the minimum tree, and use the graph to generate the minimum tree

#! /usr/bin/env python
#coding:utf-8

#The node set is defined by global variable X, which is similar to {'A':'A','B':'B','C':'C','D':'D'}. If A and B are connected, they will be changed to {'A':'B','B':'B ",...}, that is, after any two points are connected, the value s of the two points will be the same.

X = dict()      

#The initial level of each point is 0. If it is used as the end of the connection, increase 1

R = dict()

#Set the initial value of X R

def make_set(point):
    X[point] = point
    R[point] = 0

#Connection component of node

def find(point):
    if X[point] != point:
        X[point] = find(X[point])
    return X[point]

#Connecting two components (nodes)

def merge(point1,point2):
    r1 = find(point1)
    r2 = find(point2)
    if r1 != r2:
        if R[r1] > R[r2]:
            X[r2] = r1
        else:
            X[r1] = r2
            if R[r1] == R[r2]: R[r2] += 1

#Implementation of KRUSKAL algorithm

def kruskal(graph):
    for vertice in graph['vertices']:
        make_set(vertice)

    minu_tree = set()
    
    edges = list(graph['edges'])
    edges.sort()                    #Sort by side length from small to small
    for edge in edges:
        weight, vertice1, vertice2 = edge
        if find(vertice1) != find(vertice2):
            merge(vertice1, vertice2)
            minu_tree.add(edge)
    return minu_tree


if __name__=="__main__":

    graph = {
        'vertices': ['A', 'B', 'C', 'D', 'E', 'F'],
        'edges': set([
            (1, 'A', 'B'),
            (5, 'A', 'C'),
            (3, 'A', 'D'),
            (4, 'B', 'C'),
            (2, 'B', 'D'),
            (1, 'C', 'D'),
            ])
        }

    result = kruskal(graph)
    print result

There are many algorithms about the minimum tree on the Internet, most of which are defined by classes and solved by the data structure of graph. Because the data structure of graph is not well understood before, we are still gnawing at the book of data structure, hoping to make a breakthrough

Posted by ceci on Tue, 31 Dec 2019 03:04:07 -0800