Lanqiao cup minimum spanning tree shortest path python

Kruskal's algorithm is suitable for sparse graphs ( greedy )

Prim's algorithm is suitable for dense graphs or complete graphs

Minimum cost to connect all points

def root(x):
    if  p[x]!=x:
        p[x]=root(p[x])
    return p[x]
def union(x,y):
    if root(x)==root(y):
        return False
    if root(x)!=root(y):
        p[root(x)]=root(y)
    return True

points = [[3,12],[-2,5],[-4,1]]
dist = lambda x, y: abs(points[x][0] - points[y][0]) + abs(points[x][1] - points[y][1])
n = len(points)
p=[int(i) for i in range(n+1)]
edges =[]
for i in range(n):
     for j in range(i + 1, n):
        edges.append((dist(i, j), i, j))
edges.sort()        
ans, num = 0, 1
for length, x, y in edges:
    if union(x, y):
        ans += length
        num += 1
        if num == n:
            break
print(ans)

Connect all cities at the lowest cost

The number of options to reach the destination

 

 

 

 

Guess you like

Origin blog.csdn.net/m0_67105022/article/details/124046087