数据结构模板,所有需要用图解决的问题都先转化为以下数据结构,然后处理。
节点
public class Node { public int value; // 当前点的值 public int in; // 入度数 public int out; // 出度数 public ArrayList<Node> nexts; // 出度点集 public ArrayList<Edge> edges; // 出度边 public Node(int value) { this.value = value; in = 0; out = 0; nexts = new ArrayList<>(); edges = new ArrayList<>(); }}
边
public class Edge { public int weight; // 权重 public Node from; // 开始点 public Node to; // 结束点 public Edge(int weight, Node from, Node to) { this.weight = weight; this.from = from; this.to = to; }}
图
public class Graph { // 所有的点信息 // key是编号,value是点 public HashMap<Integer, Node> nodes; // 所有的边信息 public HashSet<Edge> edges; public Graph() { nodes = new HashMap<>(); edges = new HashSet<>(); }}
创建图
public class GraphGenerator { /** * matrix所有的边 * 假如是N * 3的矩阵,那么有: * [weight, from节点上面的值,to节点上面的值] * [5, 0, 7] * [3, 0, 1] */ public static Graph createGraph(int[][] matrix) { Graph graph = new Graph(); for (int i = 0; i < matrix.length; i++) { // 拿到每条边,matrix[i] int weight = matrix[i][0]; int from = matrix[i][1]; int to = matrix[i][2]; // 如果图中不包含节点,则加入到图中 if (!graph.nodes.containsKey(from)) { graph.nodes.put(from, new Node(from)); } if (!graph.nodes.containsKey(to)) { graph.nodes.put(to, new Node(to)); } Node fromNode = graph.nodes.get(from); Node toNode = graph.nodes.get(to); // 设置边 Edge newEdge = new Edge(weight, fromNode, toNode); // 设置出度点 fromNode.nexts.add(toNode); fromNode.out++; // 出度数+1 toNode.in++; // 入度数+1 // 点中加入边 fromNode.edges.add(newEdge); // 图中加入边 graph.edges.add(newEdge); } return graph; }}