一 图的表示

1. 总体表示

  1. import java.util.HashMap;
  2. import java.util.HashSet;
  3. public class Graph {
  4. // 点的集合,key为点的序号
  5. public HashMap<Integer,Node> nodes;
  6. // 边的集合
  7. public HashSet<Edge> edges;
  8. public Graph() {
  9. nodes = new HashMap<>();
  10. edges = new HashSet<>();
  11. }
  12. }

2. 点的表示

  1. import java.util.ArrayList;
  2. public class Node {
  3. // 节点的值,也可以是其他类型
  4. public int value;
  5. // 入度:有多少个节点指向这个节点
  6. public int in;
  7. // 出度:该节点指向多少个节点
  8. public int out;
  9. // 指向的点的集合
  10. public ArrayList<Node> nexts;
  11. // 该点发散出去的边的集合
  12. public ArrayList<Edge> edges;
  13. public Node(int value) {
  14. this.value = value;
  15. in = 0;
  16. out = 0;
  17. nexts = new ArrayList<>();
  18. edges = new ArrayList<>();
  19. }
  20. }

3. 边的表示

  1. public class Edge {
  2. // 边的权重
  3. public int weight;
  4. // 边出发的点
  5. public Node from;
  6. // 边的终点
  7. public Node to;
  8. public Edge(int weight, Node from, Node to) {
  9. this.weight = weight;
  10. this.from = from;
  11. this.to = to;
  12. }
  13. }

4. 示例

  1. public class GraphGenerator {
  2. /**
  3. * 一个二维数组来表示图
  4. [weight,from,to]
  5. */
  6. public static Graph createGraph(Integer[][] matrix) {
  7. Graph graph = new Graph();
  8. for (int i = 0; i < matrix.length; i++) {
  9. Integer weight = matrix[i][0];
  10. Integer from = matrix[i][1];
  11. Integer to = matrix[i][2];
  12. if (!graph.nodes.containsKey(from)) {
  13. graph.nodes.put(from, new Node(from));
  14. }
  15. if (!graph.nodes.containsKey(to)) {
  16. graph.nodes.put(to, new Node(to));
  17. }
  18. Node fromNode = graph.nodes.get(from);
  19. Node toNode = graph.nodes.get(to);
  20. Edge newEdge = new Edge(weight, fromNode, toNode);
  21. fromNode.nexts.add(toNode);
  22. fromNode.out++;
  23. toNode.in++;
  24. fromNode.edges.add(newEdge);
  25. graph.edges.add(newEdge);
  26. }
  27. return graph;
  28. }
  29. }