22.1.13 图
1.图的表示方法
-
常见的有邻接表法,邻接矩阵,数组表示的方法
-
数组表示的方法:
例如:一个二维数组为{{1,2,3},{2,4,2},{4,5,1},{2,3,4}},他表示从第一个节点到第二个节点之间有一条长度为3的路,第二个节点到第四个节点之间有一条长度为2的路.......
-
code:
public static class Edge//边集
{
public int weight;//权重
public Node from;//边的开始节点
public Node to;//边的结束节点
public Edge(int weight,Node from,Node to)
{
this.from = from;
this.to = to;
this.weight = weight;
}
}
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 Graph
{
public HashMap<Integer,Node> nodes;
public HashSet<Edge> edges;
public Graph()
{
nodes = new HashMap<>();
edges = new HashSet<>();