import java.util.ArrayList;
import java.util.Arrays;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static int n = 11;
public static int m = 31;
// 矩阵-有方向-无权-权重默认都为1.
public static int[][] graph_direct_noweight = new int[n][n];
// 矩阵-有方向-有权
public static int[][] graph_direct_weight = new int[n][n];
// 矩阵-无方向(双向)-无权
public static int[][] graph_nodirect_noweight = new int[n][n];
// 矩阵-无方向(双向)-有权
public static int[][] graph_nodirect_weight = new int[n][n];
// 邻接表-有方向-无权
public static ArrayList<ArrayList<Integer>> map_direct_noweight;
// 邻接表-有方向-有权
public static ArrayList<ArrayList<int[]>> map_direct_weight = new ArrayList<>();
// 邻接表-无方向-无权
public static ArrayList<ArrayList<Integer>> map_nodirect_noweight;
// 邻接表-无方向-有权
public static ArrayList<ArrayList<int[]>> map_nodirect_weight;
public static void build(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
graph_direct_weight[i][j] = 0;
}
}
map_direct_weight.clear();
for (int i = 0; i <= n; i++) {
map_direct_weight.add(new ArrayList<int[]>());
}
}
public static void main(String[] args) {
// 理解了带权图的建立过程,也就理解了不带权图
// 点的编号为1...n
// 例子1自己画一下图,有向带权图,然后打印结果
int n1 = 4;
int[][] edges1 = { { 1, 3, 6 }, { 4, 3, 4 }, { 2, 4, 2 }, { 1, 2, 7 }, { 2, 3, 5 }, { 3, 1, 1 } };
build(n1);
directGraph(edges1);
traversal(n1);
}
private static void traversal(int n1) {
System.out.println("邻接矩阵: 遍历图");
for (int i = 1; i <= n1; i++) {
for (int j = 1; j <= n1; j++) {
if (graph_direct_weight[i][j] != 0) {
System.out.println(i + " to " + j + " weight : " + graph_direct_weight[i][j]);
}
}
}
System.out.println("邻接表: 遍历图");
for (int i = 1; i <= n1; i++) {
ArrayList<int[]> array = map_direct_weight.get(i);
for (int[] js : array) {
System.out.println(i + " to " + js[0] + " weight : " + js[1]);
}
}
}
private static void directGraph(int[][] edges1) {
for (int i = 0; i < edges1.length; i++) {
// 邻接矩阵-带权重-有方向
graph_direct_weight[edges1[i][0]][edges1[i][1]] = edges1[i][2];
// 邻接表-带权重-有方向
map_direct_weight.get(edges1[i][0]).add(new int[] { edges1[i][1], edges1[i][2] });
}
}
}