————2020.1.18————

妖精的绣舞 提交于 2020-01-18 17:17:41

# 图 || Graph模板及实例化 #

图(Graph)数据结构本体。(Java)

 


 

 

 1 package testAlgori;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.HashSet;
 6 
 7 public class Graph {
 8     public HashMap<Integer, Node> nodes;
 9     public HashSet<Edge> edges;
10     
11     public Graph() {
12         nodes = new HashMap<>();
13         edges = new HashSet<>();
14     }
15     
16     public static class Node {
17         public int value;
18         public int in;
19         public int out;
20         public ArrayList<Node> nexts;
21         public ArrayList<Edge> edges;
22         
23         public Node(int value) {
24             this.value = value;
25             this.in = 0;
26             this.out = 0;
27             this.edges = new ArrayList<>();
28             this.nexts = new ArrayList<>();
29         }
30     }
31     
32     public static class Edge {
33         public int weight;
34         public Node from;
35         public Node to;
36         
37         public Edge(int weight, Node from, Node to) {
38             this.weight = weight;
39             this.from = from;
40             this.to = to;
41         }
42     }
43 }

 

发生器(Java)

 1 package testAlgori;
 2 
 3 import testAlgori.Graph.Edge;
 4 import testAlgori.Graph.Node;
 5 
 6 public class GraphGenerator {
 7     public static Graph createGraph(int[][] matrix) {
 8         Graph graph = new Graph();
 9         for (int i = 0; i<matrix.length; i++) {
10             int weight = matrix[i][0];
11             int from = matrix[i][1];
12             int to = matrix[i][2];
13             if (!graph.nodes.containsKey(from)) {
14                 graph.nodes.put(from, new Node(from));
15             }
16             if(!graph.nodes.containsKey(to)) {
17                 graph.nodes.put(to, new Node(to));
18             }
19             Node fromNode = graph.nodes.get(from);
20             Node toNode = graph.nodes.get(to);
21             Edge newEdge = new Edge(weight, fromNode, toNode);
22             graph.edges.add(newEdge);
23             fromNode.edges.add(newEdge);
24             fromNode.nexts.add(toNode);
25             fromNode.out++;
26             toNode.in++;
27         }
28         return graph;
29     }
30 }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!