【发布时间】:2015-12-13 00:10:43
【问题描述】:
从我读到的关于 Kruskal 算法的内容来看,似乎我们必须使用联合查找数据结构。但是为什么我不能只使用一个布尔数组来指示特定顶点是否已添加到 MST 中,而只是检查边的两个顶点是否都没有添加到 MST 中呢? IE。类似这样的东西(这类似于 Java,但是是伪代码,所以它可能无法编译):
public Queue<Edge> getMST(Graph graph) {
boolean[] visited = new boolean[graph.numVertices()];
PriorityQueue<Edge> pq = new PriorityQueue<>();
Queue<Edge> mstPath = new Queue<>();
pq.addAll(graph.edges());
while(mstPath.size() < graph.numVertices() - 1 && pq.isNotEmpty()) {
Edge curr = pq.getMin();
if (visited[curr.to] && visited[curr.from]) continue; // ignore because both vertices of this edge are in MST
mstPath.add(curr);
visited[curr.to] = true;
visited[curr.from] = true;
}
return mstPath;
}
那么我为什么要使用 Union Find 数据结构呢?上面的方法不正确吗?
【问题讨论】: