图 - Java实现无向带权图的邻接矩阵表示法

时间:2025-03-07 17:02:00
package com.lagou; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author 云梦归遥 * @date 2022/5/20 12:30 * @description 无向带权图 - 邻接矩阵法 */ public class NoDirectionWeightTuMethod { private List<Object> nodeList; // 存储所有节点的集合 private int[][] adjacencyMatrix; // 邻接矩阵 private int edge; // 边的数量 public NoDirectionWeightTuMethod(int num){ nodeList = new ArrayList<>(num); adjacencyMatrix = new int[num][num]; edge = 0; } // 添加节点 public NoDirectionWeightTuMethod insert(Object node){ nodeList.add(node); return this; } // 查找节点 public String select(Object node){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("【" + node + "】= "); int index = nodeList.indexOf(node); // 获取索引 if (index >= 0){ // 节点存在 for (int i = 0; i < adjacencyMatrix.length; i++){ if (adjacencyMatrix[index][i] > 0){ stringBuilder.append("【<" + node + ", " + nodeList.get(i) + "> - weight: " + adjacencyMatrix[index][i] + "】 => "); } } } else { stringBuilder.append("null"); } String result = stringBuilder.toString(); result = result.substring(0, result.lastIndexOf(" => ")); return result; } // 获取节点的个数 public int getNodeNum(){ return nodeList.size(); } // 添加边(权重) public NoDirectionWeightTuMethod addEdge(Object object1, Object object2, int weight){ if (nodeList.contains(object1) && nodeList.contains(object2)){ int index1 = nodeList.indexOf(object1); int index2 = nodeList.indexOf(object2); adjacencyMatrix[index1][index2] = weight; adjacencyMatrix[index2][index1] = weight; } return this; } // 获取权重 public int getWeight(Object object1, Object object2){ int result = Integer.MAX_VALUE; // 默认 int 最大值 if (nodeList.contains(object1) && nodeList.contains(object2)){ int index1 = nodeList.indexOf(object1); int index2 = nodeList.indexOf(object2); result = adjacencyMatrix[index1][index2]; } return result; } // 判断边是否存在 public boolean hasEdge(Object object1, Object object2){ boolean result = false; if (nodeList.contains(object1) && nodeList.contains(object2)){ int index1 = nodeList.indexOf(object1); int index2 = nodeList.indexOf(object2); if (adjacencyMatrix[index1][index2] > 0){ result = true; } } return result; } // 获取边的数量 public int getEdgeNum(Object object){ int num = Integer.MAX_VALUE; if (nodeList.contains(object)){ num = 0; int index = nodeList.indexOf(object); for (int i = 0; i < adjacencyMatrix.length; i++){ if (adjacencyMatrix[index][i] > 0){ num++; } } } return num; } // 获取 邻接矩阵 public String getAdjacencyMatrix(){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(" " + Arrays.toString(nodeList.toArray()) + "\n"); for (int i = 0; i < adjacencyMatrix.length; i++){ stringBuilder.append(nodeList.get(i) + " " + Arrays.toString(adjacencyMatrix[i]) + "\n"); } return stringBuilder.toString(); } }