import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class test35 { //点的定义 public static 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 static 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 static class Graph{ public HashMap<Integer ,Node> nodes;//编号为多少的点那个点的结构是什么 public HashSet<Edge> edges;//所有的边装在边集里 public Graph(){ nodes = new HashMap<>(); edges = new HashSet<>(); } } //形成图结构 //传进来二维数组,每行有三个值,分别为权重,from和to这三个属性代表了每个点的结构 public static Graph createGraph(Integer[][] matrix) { Graph graph = new Graph(); for (int i = 0; i < matrix.length; i++) { //建立数据 Integer weight = matrix[i][0]; Integer from = matrix[i][1]; Integer to = matrix[i][2]; //如果图里没有from这个点,就新建 if (!graph.nodes.containsKey(from)) { graph.nodes.put(from, new Node(from)); } //如果图里没有to这个点,就新建 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++; toNode.in++; fromNode.edges.add(newEdge); graph.edges.add(newEdge); } return graph; } }
08-24
691
12-13
4442
12-22
1377