最佳方法在Java中创建邻接表是什么?

huangapple go评论72阅读模式
英文:

Best Way to create Adjacency List in java?

问题

一般来说,要在Java中创建n个节点的邻接表,我们需要创建一个额外的循环来用空列表填充该列表,如下所示-

for (int i = 0; i < n; i++)
    adj.add(new ArrayList<>());

现在我们必须添加元素,但由于这个额外的循环,它会浪费时间。有没有其他更好的方法来创建邻接表?

英文:

In general, to create Adjacency list of n node in java, we need to create an extra loop to fill the list with empty list like below-

for(int i=0;i&lt;n;i++)
    adj.add(new ArrayList&lt;&gt;());

Now we had to had to add the elements,but because of this extra loop its wasting the time.
Is there any other best way to create the adjacency list??????

答案1

得分: 1

如果我需要对图进行紧凑的表示,并且可以按顺序获取每个顶点的邻居,我通常会这样做:

// 顶点的连接邻接表按顺序连接在一起
ArrayList<Integer> adjList = new ArrayList<>();

// 每个顶点的邻接表在adjList中的结束位置
ArrayList<Integer> adjListEnds = new ArrayList<>();

for (int i = 0; i < num_vertexes; ++i) {
    for (int adj : getNeighbors(i)) {
        adjList.add(adj);
    }
    adjListEnds.add(adjList.size());
}

现在,要获取任何顶点的邻居:

int s = vertex > 0 ? adjListEnds.get(vertex - 1) : 0;
int e = adjListEnds.get(vertex);
for (int i = s; i < e; ++i) {
    processNeighbor(vertex, adjList.get(i));
}

当然,如果你希望它真正紧凑,那么你应该使用类似于保存原始int而不是Integer的数组列表。有时我会自己编写,有时我会使用GNU Trove。

英文:

If I need to make a compact representation of a graph, and I can get the neighbors for each vertex in sequence, I often do it like this:

//Concatenated adjacency lists for each vertex in order
ArrayList&lt;Integer&gt; adjList = new ArrayList&lt;&gt;();

//For each vertex, the end of its adjacency list in adjList
ArrayList&lt;Integer&gt; adjListEnds = new ArrayList&lt;&gt;();

for (int i=0; i&lt;num_vertexes; ++i) {
    for (int adj : getNeighbors(i)) {
        adjList.add(adj);
    }
    adjListEnds.add(adjList.size());
}

Now, to get the neighbors of any vertex:

int s = vertex&gt;0 ? adjListEnds.get(vertex-1) : 0;
int e = adjListEnds.get(vertex);
for (int i = s; i&lt;e; ++i) {
    processNeighbor(vertext, adjList.get(i));
}

Of course, if you want it to be really compact, then you should use something like an array list that holds primitive ints instead of Integers. Sometimes I roll my own. Sometimes I use gnu trove.

huangapple
  • 本文由 发表于 2020年9月12日 01:08:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63851477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定