public class GraphStrcture{
public static class Graph{
public HashMap<Integer,Node> nodes;//点集,每一个记录着当前点的值和真正的点
public HashSet<Edge> edges;//边集
public Graph(){
nodes = new HashMap<>();
edges = new HashSet<>();
}
}
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;
}
}
//将不熟悉的图结构转换为熟悉的结构
//matrix 所有的边
// N * 3的矩阵
// [weight,from节点上的值,to节点上面的值]
public static Graph creatGraph(Integer[][] matrix){//该图的结构是三列的矩阵,记录出度,入度,权重,如何转化为熟悉的图结构
Graph graph = new Graph();
for(int i = 0; i < matrix.length; i++){
Integer from = matrix[i][0];
Integer to = matrix[i][1];
Integer weight = 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);//from的邻居里把to点加上
fromNode.out++;
toNode.in++;
fromNode.edges.add(newEdge);
graph.edges.add(newEdge);
}
return graph;
}
}
将不熟悉的图结构转化为熟悉的图结构模板