Undirected Graph implementation in Java
Yuxuan Wu Lv13

Graph implementation

adjacency matrix

本质是一个大小为v(vertex的数量) 的数组,每个数组存储了一个LinkedList对象,这里代表的是与当前vertex相连的数

image-20211003100616294

image-20211003100648307

这里的Queue不是java内置的队列,而是调用之前实现的队列,这里用linkedlist来代替

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package graph;

import java.util.LinkedList;

public class Graph {
// vertex
private final int V;

// edge
private int E;

// adjacency matrix, an array storing the Queue
private LinkedList[] adj;

// construct the graph
public Graph(int V) {
this.V = V;
this.E = 0;
this.adj = new LinkedList[V];

for (int i = 0; i < adj.length; i++) {
adj[i] = new LinkedList<>();
}
}

// return the number of vertex V
public int V() {
return V;
}

// return the number of edge E
public int E() {
return E;
}

public void addEdge(int v, int w) {
// add w to queue adj[v], so vertex v would have w in their queue
adj[v].add(w);

// reversely add v to vertex w
adj[w].add(v);
E++;
}

// return all the vertex that are frontiers of vertex v
public LinkedList<Integer> adj(int v) {
return adj[v];
}
}
  • Post title:Undirected Graph implementation in Java
  • Post author:Yuxuan Wu
  • Create time:2021-10-03 09:50:23
  • Post link:yuxuanwu17.github.io2021/10/03/2021-10-03-Undirected-Graph-implementation-in-Java/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.