[英]Representing a directed acyclic graph as a 2-dimensional array in Java
How can I represent a directed acyclic graph as a 2-dimensional array if each row contains the immediate out-neighbours of a particular node. 如果每一行包含特定节点的直接邻居,如何将有向无环图表示为二维数组。 For example, if I have an array int [] [] edges, edges[0] = {1,2,3} means there are edges from node 0 to nodes 1, 2 and 3. 例如,如果我有一个数组int [] [] edges,edges [0] = {1,2,3}表示存在从节点0到节点1、2和3的边缘。
int n;
List<Integer>[] adj;
AdjacencyLists(int n) {
adj = (List<Integer>[])new List[n];
for (int i = 0; i < n; i++)
adj[i] = new ArrayList<Integer>(Integer.class);
}
.....
adj[a].add(b); // a -> b edge
If you have to use a 2D array - given that a 2D array at least in Java can't be sparse - then you need to allocate an NxN array: boolean[][] edges = new boolean[n][n];
如果必须使用2D数组-至少在Java中不能稀疏使用2D数组-那么您需要分配一个NxN数组: boolean[][] edges = new boolean[n][n];
n-1
rows. 您需要考虑所有节点都在一条链中的简并情况,因此您需要n-1
行。 n-1
columns. 您需要允许一个根植于任何节点上的星形,因此需要n-1
列。 j
, position k
for an edge from j
-> k
. 将地址存储在数组中要复杂得多(考虑到大小必须如此之大),而不是简单地在行j
存储“是”,即从j
> k
到k
的边存储位置。 And it's a lot faster to update the latter. 而且更新后者要快得多。 Obviously the sensible approach would be a HashMap from source node to a HashSet of target nodes, but that's apparently not what you're looking for. 显然,明智的方法是从源节点到目标节点的HashSet的HashMap,但这显然不是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.