我是编程和尝试自己学习数据结构的新手。我正在尝试使用邻接列表来实现一个未加权的图类,但是我在实现getAdjacentVertices方法时遇到了麻烦,而且我并不完全知道addEdge方法是如何实际工作的,特别是如何实现insertAtTheBeginning方法。请帮助我,我正在使用的这本书并没有真正解释这个主题。*
enter code here
public class Graph {
private ArrayList<Integer> vertices;
private ListNode[] edges;
private int vertexCount = 0;
public Graph(int vertexCount){
this.vertexCount = vertexCount;
vertices = new ArrayList<Integer>();
edges = new ListNode[vertexCount];
for(int i = 0; i < vertexCount; i++){
vertices.add(i);
edges[i] = new ListNode ();
}
}
public void addEdge(int source, int destination){
int i = vertices.indexOf(source);
int j = vertices.indexOf(destination);
if(i != -1 || j != -1){
edges[i].insertAtBeginning(destination);
edges[j].insertAtBeginning(source);
}
}
public int getNumberVertices() {
return vertexCount;
}
public Object getAdjacentVertices(int currentVertex) {
}
}
答案 0 :(得分:0)
回答你的问题,
getAdjacentVertices(i)
只需返回i
的{{1}}个元素。edges
不必添加到开头。除非您有特定原因在邻居列表上强加订单,否则大多数图算法都不需要一个。其他几点:
addEdge()
- 1.因此,除非您的顶点有有效负载(名称,成本等),否则您可以取消n
数组。vertices
命名,以明确该图表是无向的(即,UndirectedGraph
邻居列表中v
出现时u
u
1}}也会出现在v
的邻居列表中。List<Integer>
作为邻接列表,并将其作为LinkedList
实施。大多数图算法只需要能够迭代邻接列表,而不是随机访问(ArrayList
提供的)。addEdge()
不执行验证。根据输入的来源,您可能需要检查0≤u, v
&lt; vertexCount
并且边缘(u, v)
尚不存在。为简洁起见,我将main()
方法包含在同一个类中。
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
public class UndirectedGraph {
private Vector<List<Integer>> edges;
private int vertexCount = 0;
public UndirectedGraph(int vertexCount) {
this.vertexCount = vertexCount;
edges = new Vector<List<Integer>>(vertexCount);
for (int i = 0; i < vertexCount; i++){
edges.addElement(new LinkedList<Integer>());
}
}
public void addEdge(int u, int v) {
edges.get(u).add(v);
edges.get(v).add(u);
}
public int getNumberVertices() {
return vertexCount;
}
public Object getAdjacentVertices(int u) {
return edges.get(u);
}
public static void main(String [] args) {
UndirectedGraph g = new UndirectedGraph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
for (int i = 0; i < g.getNumberVertices(); i++) {
System.out.println("Neighbors of node " + i + ": " + g.getAdjacentVertices(i));
}
}
}