摘自@左程云https://github.com/algorithmzuo/algorithm-journey/blob/main/src/class059/Code01_CreateGraph.java
public class Mian {
// 点的最大数量
public static int MAXN = 11;
// 边的最大数量
// 只有链式前向星方式建图需要这个数量
// 注意如果无向图的最大数量是m条边,数量要准备m*2
// 因为一条无向边要加两条有向边
public static int MAXM = 21;
// 链式前向星方式建图
public static int[] head = new int[MAXN];
public static int[] next = new int[MAXM];
public static int[] to = new int[MAXM];
// 如果边有权重,那么需要这个数组
public static int[] weight = new int[MAXM];
public static int cnt;
public static void build(int n) {
// 链式前向星清空
cnt = 1;
Arrays.fill(head, 1, n + 1, 0);
}
// 链式前向星加边
public static void addEdge(int u, int v, int w) {
// u -> v , 边权重是w
next[cnt] = head[u];
to[cnt] = v;
weight[cnt] = w;
head[u] = cnt++;
}
// 建立有向图带权图
public static void directGraph(int[][] edges) {
// 链式前向星建图
for (int[] edge : edges) {
addEdge(edge[0], edge[1], edge[2]);
}
}
// 建立无向图带权图
public static void undirectGraph(int[][] edges) {
// 链式前向星建图
for (int[] edge : edges) {
addEdge(edge[0], edge[1], edge[2]);
addEdge(edge[1], edge[0], edge[2]);
}
}
// 遍历
public static void traversal(int n) {
System.out.println("链式前向星 :");
for (int i = 1; i <= n; i++) {
System.out.print(i + "(邻居、边权) : ");
// 注意这个for循环,链式前向星的方式遍历
for (int ei = head[i]; ei > 0; ei = next[ei]) {
System.out.print("(" + to[ei] + "," + weight[ei] + ") ");
}
System.out.println();
}
}
}