数据结构模板,所有需要用图解决的问题都先转化为以下数据结构,然后处理。

节点

  1. public class Node {
  2. public int value; // 当前点的值
  3. public int in; // 入度数
  4. public int out; // 出度数
  5. public ArrayList<Node> nexts; // 出度点集
  6. public ArrayList<Edge> edges; // 出度边
  7. public Node(int value) {
  8. this.value = value;
  9. in = 0;
  10. out = 0;
  11. nexts = new ArrayList<>();
  12. edges = new ArrayList<>();
  13. }
  14. }

  1. public class Edge {
  2. public int weight; // 权重
  3. public Node from; // 开始点
  4. public Node to; // 结束点
  5. public Edge(int weight, Node from, Node to) {
  6. this.weight = weight;
  7. this.from = from;
  8. this.to = to;
  9. }
  10. }

  1. public class Graph {
  2. // 所有的点信息
  3. // key是编号,value是点
  4. public HashMap<Integer, Node> nodes;
  5. // 所有的边信息
  6. public HashSet<Edge> edges;
  7. public Graph() {
  8. nodes = new HashMap<>();
  9. edges = new HashSet<>();
  10. }
  11. }

创建图

  1. public class GraphGenerator {
  2. /**
  3. * matrix所有的边
  4. * 假如是N * 3的矩阵,那么有:
  5. * [weight, from节点上面的值,to节点上面的值]
  6. * [5, 0, 7]
  7. * [3, 0, 1]
  8. */
  9. public static Graph createGraph(int[][] matrix) {
  10. Graph graph = new Graph();
  11. for (int i = 0; i < matrix.length; i++) {
  12. // 拿到每条边,matrix[i]
  13. int weight = matrix[i][0];
  14. int from = matrix[i][1];
  15. int to = matrix[i][2];
  16. // 如果图中不包含节点,则加入到图中
  17. if (!graph.nodes.containsKey(from)) {
  18. graph.nodes.put(from, new Node(from));
  19. }
  20. if (!graph.nodes.containsKey(to)) {
  21. graph.nodes.put(to, new Node(to));
  22. }
  23. Node fromNode = graph.nodes.get(from);
  24. Node toNode = graph.nodes.get(to);
  25. // 设置边
  26. Edge newEdge = new Edge(weight, fromNode, toNode);
  27. // 设置出度点
  28. fromNode.nexts.add(toNode);
  29. fromNode.out++; // 出度数+1
  30. toNode.in++; // 入度数+1
  31. // 点中加入边
  32. fromNode.edges.add(newEdge);
  33. // 图中加入边
  34. graph.edges.add(newEdge);
  35. }
  36. return graph;
  37. }
  38. }