java - 如何实现并查算法?

标签 java graph vertices kruskals-algorithm union-find

我正在尝试实现并查算法,但我查找的所有实现都使用整数。我需要实现该算法,以便可以通过以下方式调用 union() 和connected() 方法: union(Vertex v, Vertex, w) -connected(Vertex v, Vertex w)

我已经尝试调整我的算法以使其能够处理顶点,但我不知道如何替换父属性和排名属性以使其工作。请帮忙:(

公开课用友{

private int[] parent;  // parent[i] = parent of i
private byte[] rank;   // rank[i] = rank of subtree rooted at i (never more than 31)
private int count;     // number of components

/**
 * Initializes an empty union–find data structure with {@code n} sites
 * {@code 0} through {@code n-1}. Each site is initially in its own 
 * component.
 *
 * @param  n the number of sites
 * @throws IllegalArgumentException if {@code n < 0}
 */
public UF(int n) {
    if (n < 0) throw new IllegalArgumentException();
    count = n;
    parent = new int[n];
    rank = new byte[n];
    for (int i = 0; i < n; i++) {
        parent[i] = i;
        rank[i] = 0;
    }
}

/**
 * Returns the component identifier for the component containing site {@code p}.
 *
 * @param  p the integer representing one site
 * @return the component identifier for the component containing site {@code p}
 * @throws IllegalArgumentException unless {@code 0 <= p < n}
 */
public int find(int p) {
    validate(p);
    while (p != parent[p]) {
        parent[p] = parent[parent[p]];    // path compression by halving
        p = parent[p];
    }
    return p;
}

/**
 * Returns the number of components.
 *
 * @return the number of components (between {@code 1} and {@code n})
 */
public int count() {
    return count;
}

/**
 * Returns true if the the two sites are in the same component.
 *
 * @param  p the integer representing one site
 * @param  q the integer representing the other site
 * @return {@code true} if the two sites {@code p} and {@code q} are in the same component;
 *         {@code false} otherwise
 * @throws IllegalArgumentException unless
 *         both {@code 0 <= p < n} and {@code 0 <= q < n}
 */
public boolean connected(int p, int q) {
    return find(p) == find(q);
}

/**
 * Merges the component containing site {@code p} with the 
 * the component containing site {@code q}.
 *
 * @param  p the integer representing one site
 * @param  q the integer representing the other site
 * @throws IllegalArgumentException unless
 *         both {@code 0 <= p < n} and {@code 0 <= q < n}
 */
public void union(int p, int q) {
    int rootP = find(p);
    int rootQ = find(q);
    if (rootP == rootQ) return;

    // make root of smaller rank point to root of larger rank
    if      (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
    else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
    else {
        parent[rootQ] = rootP;
        rank[rootP]++;
    }
    count--;
}

// validate that p is a valid index
private void validate(int p) {
    int n = parent.length;
    if (p < 0 || p >= n) {
        throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));  
    }
}

}

最佳答案

在标准算法中,每个顶点都会被赋予一个int id,它表示它在数组中的位置。所以这意味着 parent[0] 包含顶点 0 的父级的 id 等等。

实际上,您可以将数组视为从 int 到其他内容的非常有效的映射。如果您将 int 替换为更复杂的类型,那么您需要开始使用 Map 而不是数组。

因此,如果您想使用名为 Vertex 的类来表示顶点,那么您需要以不同的方式声明父级和等级:

Map<Vertex,Vertex> parent = new HashMap<>();
Map<Vertex,Rank> rank = new HashMap<>();

如果您想坚持当前方案,您可以将 Rank 替换为 Byte - 尽管使用类可能是更好的封装。

然后您将得到如下所示的代码:

while (!vertex.equals(parent.get(vertex))) {
    parent.put(vertex, parent.get(parent.get(vertex)));
    vertex = parent.get(vertex);
}
return vertex;

需要注意的一件事是,如果您要使用 Vertex 作为 map 的键(正如我所建议的),那么您必须实现equalshashCode 方法。

关于java - 如何实现并查算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56230697/

相关文章:

java - 如何正确关闭 Swing 应用程序

python - 使用 numpy 表示具有未知结构的(可能很大)图的有效方法?

r - 在 R 中创建累积步骤图

c++ - DirectX 11 顶点坐标

java - 如何根据嵌入的属性进行排序并通过规范限制结果的数量?

java - groovy 或 java : how to retrieve a block of comments using regex from/** ***/?

php - 一个适合我的基准测试的线图生成器?

algorithm - 为什么 igraph spinglass 给我 'Cannot work with unconnected graph' ?

mysql - 如何将点 append 到 LINESTRING SQL

java - 可以将包名称变量传递到 Android 源代码中吗?