Menu
CoddyTech

伪代码

Coddy 克鲁斯卡尔算法:图算法 课程的第 4 课,共 9 课。

kruskal(n, edges):
   parent[i] = i for all i          # each vertex its own set
   total = 0
   repeat until all edges considered:
      pick the unused edge (u, v, w) with the smallest w
      ru = find(u); rv = find(v)
      if ru != rv:                   # no cycle
         parent[ru] = rv             # union
         total += w
   return total

find(x):
   while parent[x] != x: x = parent[x]
   return x
  • 每轮选择未使用边中权重最小的一条(最小值选择),这样就不需要单独排序。
  • find 会向上遍历到根节点;union 只需将一个根节点赋值给另一个根节点。

亲手试试

这节课没有代码挑战。

quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

克鲁斯卡尔算法:图算法中的所有课

自己练习: C 在线编译器