图的表示一般是可以使用邻接表、邻接矩阵……来表示的,网上大把,这里介绍的是一种更为强大的方式,基本上可以应对所有的关于图的算法,例如拓扑排序、深搜、广搜、Kruskal、Prim、Dijkstra。
创建图的时候是传递一个二维数组过来,matrix[i][0]是权重,matrix[i][1]是起始点的值,matrix[i][2]是终止点的值,最后返回一张图。
public class GraphGenerator { //创建图 public static Graph creatGraph(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); //新建一条from到to 的边 Edge newEdge = new Edge(weight, fromNode, toNode); //fromNode与toNode建立关联,将toNode放到fromNode的next集合 fromNode.nexts.add(toNode);//graph.nodes.get(from).nextx.add(toNode); //改变fromNode与toNode的入度与出度 fromNode.out++; toNode.in++; //将建立好的边加入到边集(Graph,Node) graph.edges.add(newEdge); fromNode.edges.add(newEdge); } return graph; } }
import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class Graph { //点集,边集 public HashMap<Integer, Node>nodes;//点的编号,实际对应的点 public Set<Edge>edges; public Graph(){ nodes = new HashMap<Integer, Node>(); edges = new HashSet<Edge>(); } }
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; } }
import java.util.ArrayList; public class Node { public int value;//值 public int in;//入度,多少个节点指向我 public int out;//出度,我指向多少个节点 public ArrayList<Node>nexts;//从我出发能到达的邻居节点 public ArrayList<Edge>edges;//从我出发 的边的集合(from) public Node(int value){ this.value = value; in = 0; out = 0; nexts = new ArrayList<Node>(); edges = new ArrayList<Edge>(); } }