【代码】图之无向图

前言

图之无向图的Java版API实现

源代码

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
package com;

public class Graph {

private final int nodeLength;
private int lineLength;
private Queue<Integer>[] adj;

Graph(int nodeLength) {
// 初始化所有顶点的数量
this.nodeLength = nodeLength;
// 初始化所有边的数量
this.lineLength = 0;
// 初始化邻接表
this.adj = new Queue[nodeLength];
// 为每一个序列的值初始化一个子序列
for (int i = 0; i < adj.length; i++) {
adj[i] = new Queue<Integer>();
}
}

// 获取所有的定点
public int getNodeLength() {
return nodeLength;
}

// 获取所有的边
public int getLineLength() {
return lineLength;
}

// 指定两个定点创建它的边
public void addEdge(int node1, int node2) {
adj[node1].enQueue(node2);
adj[node2].enQueue(node1);
// 边的数量自增
lineLength++;
}

// 获取和指定顶点相邻的所有顶点
public Queue<Integer> adj(int node) {
return adj[node];
}

}

完成

参考文献

哔哩哔哩——黑马程序员