1:邻接表法表示图
2:矩阵表法表示图
自己到自己的距离是0,a到b的距离是3,c到a的距离是7,a到c的距离是正无穷。a到f没有直接的边,那距离就是正无穷。
3:点结构
package algorithmbasic.class17;
import java.util.ArrayList;
//点结构的描述
public 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;
this.in = 0;
this.out = 0;
this.nexts = new ArrayList<>();
this.edges = new ArrayList<>();
}
}
4:边结构
package algorithmbasic.class17;
public 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;
}
}
5:图结构
package algorithmbasic.class17;
import java.util.HashMap;
import java.util.HashSet;
//图结构
public class Graph {
/**
* 属性
*/
HashMap<Integer, Node> nodes;
HashSet<Edge> edges;
/**
* 构造器
*/
public Graph() {
this.nodes = new HashMap<>();
this.edges = new HashSet<>();
}
}
6:接口转化器
package algorithmbasic.class17;
//接口转化器
//将一些特殊结构图的表示方法转化成我们熟悉的图的表示方法。
public class GraphGenerator {
// matrix 所有的边。
// N*3 的矩阵。
// [weight, from节点上面的值,to节点上面的值]。
//
// [ 5 , 0 , 7] -> 0号节点指向7号节点,边的权重大小是5。
// [ 3 , 0, 1] -> 0号节点指向1号节点,边的权重大小是3。
//
public static Graph createGraph(int[][] matrix) {
Graph graph = new Graph();
//遍历每一条边。
for (int i = 0; i < matrix.length; i++) {
//起始值
int fromValue = matrix[i][1];
//终点值
int toValue = matrix[i][2];
//边的权重
int edgeWeight = matrix[i][0];
//如果没有一个节点的值是fromValue,那就创建这个节点。
if (!graph.nodes.containsKey(fromValue)) {
graph.nodes.put(fromValue, new Node(fromValue));
}
if (!graph.nodes.containsKey(toValue)) {
graph.nodes.put(toValue, new Node(toValue));
}
//拿到这条边的起始节点与终止接点。
Node formNode = graph.nodes.get(fromValue);
Node toNode = graph.nodes.get(toValue);
//创建这条边。
Edge edge = new Edge(edgeWeight, formNode, toNode);
graph.edges.add(edge);
//编辑formNode的in , out , nexts, edgs
formNode.out++;
formNode.nexts.add(toNode);
formNode.edges.add(edge);
//编辑toNode的in out nexts edges
toNode.in++;
}
return graph;
}
}