| import java.util.ArrayList; |
| import java.util.Arrays; |
| |
| |
| public class Main { |
| |
| public static int n = 11; |
| public static int m = 31; |
| |
| |
| 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) { |
| |
| |
| |
| 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] }); |
| } |
| } |
| |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统