[英]How to find the list of edges incident to a particular vertex
I tried the following but I'm not sure that it is correct.我尝试了以下但我不确定它是否正确。
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
public static ArrayList<ArrayList<Integer>> incidentEdges(int v) {
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
if(a[v][j] == 1) {
list.get(v).get(new Edge(start, destination));
list.get(j).get(new Edge(start, destination);
}
}
}
return list;
}
The array a is an adjacency matrix and the parameter v is the vertex of an undirected graph.数组a是邻接矩阵,参数v是无向图的顶点。 If there is an edge between vertex v and j then we add the edge incident to vertex v .
如果顶点v和j之间有一条边,那么我们将边添加到顶点v 。
Since you have already stored the edges in an adjacency matrix, you can simply query it.由于您已经将边存储在邻接矩阵中,因此您可以简单地查询它。 Set your
i
to v (since you are not even using i
in the first place), and then check all vertices that are connected.将你的
i
设置为 v (因为你一开始甚至没有使用i
),然后检查所有连接的顶点。
public static ArrayList<Integer> incidentEdges(int v) {
ArrayList<Integer> result = new ArrayList<>();
for(int i = 0; i < a[v].length; i++) {
if(a[v][i] == 1) {
result.add(a[v].get(i));
}
}
return result;
}
If you get control of the input (ie before making the adjacency matrix), what you want is an adjacency list : Where each list[start]
points to an ArrayList<Integer>
(representing the connected vertices).如果您控制了输入(即在制作邻接矩阵之前),您想要的是一个邻接列表:其中每个
list[start]
指向一个ArrayList<Integer>
(代表连接的顶点)。 I would avoid the use of ArrayList
since the number of vertices is already known.我会避免使用
ArrayList
因为顶点的数量是已知的。 So I would instead use ArrayList<Integer>[] list
instead.所以我会改用
ArrayList<Integer>[] list
。 This definitely makes it easier to code.这无疑使编码更容易。
Here is an example of generating the adjacency list from an adjacency matrix这是从邻接矩阵生成邻接列表的示例
static ArrayList<Integer>[] list;
public static ArrayList<Integer>[] generateAl(int v) {
list = new ArrayList[a.length];
for(int i = 0; i < a.length; i++) {
list[i] = new ArrayList<>();
for(int j = 0; j < a[i].length; j++) {
if(a[i][j] == 1) {
list[i].add(j);
}
}
}
return list;
}
public static ArrayList<Integer> incidentEdges(int v) {
return list[v];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.