# andyRon/swift-algorithm-club-cn

Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
Images
MinimumSpanningTree.playground

# 最小生成树（加权图）（Minimum Spanning Tree (Weighted Graph)）

### Kruskal算法

Sort the edges base on weight. Greedily select the smallest one each time and add into the MST as long as it doesn't form a cycle. 根据权重对边进行排序。每次贪婪地选择最小的一个并且只要它不形成循环就加入MST。
Kruskal的算法使用并查集 数据结构来检查是否有任何其他边导致循环。逻辑是将所有连接的顶点放在同一个集合中（在并查集的概念中）。如果来自新边的两个顶点不属于同一个集合，那么将该边添加到MST中是安全的。

```// Initialize the values to be returned and Union Find data structure.
var cost: Int = 0
var tree = Graph<T>()
var unionFind = UnionFind<T>()
for vertex in graph.vertices {

// Initially all vertices are disconnected.
// Each of them belongs to it's individual set.
}```

`let sortedEdgeListByWeight = graph.edgeList.sorted(by: { \$0.weight < \$1.weight })`

```for edge in sortedEdgeListByWeight {
let v1 = edge.vertex1
let v2 = edge.vertex2

// Same set means the two vertices of this edge were already connected in the MST.
// Adding this one will cause a cycle.
if !unionFind.inSameSet(v1, and: v2) {
// Add the edge into the MST and update the final cost.
cost += edge.weight

// Put the two vertices into the same set.
unionFind.unionSetsContaining(v1, and: v2)
}
}```

### Prim算法

Prim算法不会对所有边进行预排序。相反，它使用优先队列来维护正在运行的已排序的下一个可能的顶点。

```// Initialize the values to be returned and Priority Queue data structure.
var cost: Int = 0
var tree = Graph<T>()
var visited = Set<T>()

// In addition to the (neighbour vertex, weight) pair, parent is added for the purpose of printing out the MST later.
// parent is basically current vertex. aka. the previous vertex before neigbour vertex gets visited.
var priorityQueue = PriorityQueue<(vertex: T, weight: Int, parent: T?)>(sort: { \$0.weight < \$1.weight })```

`priorityQueue.enqueue((vertex: graph.vertices.first!, weight: 0, parent: nil))`
```// Take from the top of the priority queue ensures getting the least weight edge.
while let head = priorityQueue.dequeue() {
if visited.contains(vertex) {
continue
}

// If the vertex hasn't been visited before, its edge (parent-vertex) is selected for MST.
visited.insert(vertex)
if let prev = head.parent { // The first vertex doesn't have a parent.
}

// Add all unvisted neighbours into the priority queue.
if let neighbours = graph.adjList[vertex] {
for neighbour in neighbours {
let nextVertex = neighbour.vertex
if !visited.contains(nextVertex) {
priorityQueue.enqueue((vertex: nextVertex, weight: neighbour.weight, parent: vertex))
}
}
}
}```

You can’t perform that action at this time.