一、拓扑排序概念
- 对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边<u,v>∈E(G),则u在线性序列中出现在v之前。通常,这样的线性序列称为满足拓扑次序(Topological Order)的序列,简称拓扑序列。
- 简单的说,由某个集合上的一个偏序得到该集合上的一个全序,这个操作称之为拓扑排序。
二、理解
- 在一个有向图中,对所有的节点进行排序,要求没有一个节点指向它前面的节点。
- 先统计所有节点的入度,对于入度为0的节点就可以分离出来,然后把这个节点指向的节点的入度减一。
- 一直做改操作,直到所有的节点都被分离出来。
- 如果最后不存在入度为0的节点,但还存在节点,那就说明有环,不存在拓扑排序,也就是很多题目的无解的情况。
三、基本实现思路
- 先把入度为0 的节点找到并打印
- 删掉入度为0的节点,继续循环1的步骤,直至图为null。
四、算法具体思路
第一种方式
是遍历整个图中的顶点,找出入度为0的顶点,然后标记删除该顶点,更新相关顶点的入度,由于图中有V个顶点,每次找出入度为0的顶点后会更新相关顶点的入度,因此下一次又要重新扫描图中所有的顶点。故时间复杂度为O(V^2)
问题:由于删除入度为0的顶点时,只会更新与它邻接的顶点的入度,即只会影响与之邻接的顶点。但是上面的方式却遍历了图中所有的顶点的入度。
第二种方式(更优的算法)
先将入度为0的顶点放在栈或者队列中。当队列不空时,删除一个顶点v,然后更新与顶点v邻接的顶点的入度。只要有一个顶点的入度降为0,则将之入队列。此时,拓扑排序就是顶点出队的顺序。该算法的时间复杂度为O(V+E)
五、拓扑排序方法实现
该算法借助队列来实现时,感觉与 二叉树的 层序遍历算法很相似啊。说明这里面有广度优先的思想。
第一步:遍历图中所有的顶点,将入度为0的顶点 入队列。
第二步:从队列中出一个顶点,打印顶点,更新该顶点的邻接点的入度(减1),如果邻接点的入度减1之后变成了0,则将该邻接点入队列。
第三步:一直执行上面 第二步,直到队列为空。
public void topoSort() throws Exception{int count = 0;//判断是否所有的顶点都出队了,若有顶点未入队(组成环的顶点),则这些顶点肯定不会出队Queue<Vertex> queue = new LinkedList<>();// 拓扑排序中用到的栈,也可用队列.//扫描所有的顶点,将入度为0的顶点入队列Collection<Vertex> vertexs = directedGraph.values();for (Vertex vertex : vertexs)if(vertex.inDegree == 0)queue.offer(vertex);//度为0的顶点出队列并且更新它的邻接点的入度while(!queue.isEmpty()){Vertex v = queue.poll();System.out.print(v.vertexLabel + " ");//输出拓扑排序的顺序count++;for (Edge e : v.adjEdges)if(--e.endVertex.inDegree == 0)queue.offer(e.endVertex);}if(count != directedGraph.size())throw new Exception("Graph has circle");}
第7行for循环:先将图中所有入度为0的顶点入队列。
第11行while循环:将入度为0的顶点出队列,并更新与之邻接的顶点的入度,若邻接顶点的入度降为0,则入队列(第16行if语句)。
第19行if语句判断图中是否有环。因为,只有在每个顶点出队时,count++。对于组成环的顶点,是不可能入队列的,因为组成环的顶点的入度不可能为0(第16行if语句不会成立).
因此,如果有环,count的值 一定小于图中顶点的个数。
完整代码实现
DirectedGraph.java中定义了图 数据结构,(图的实现可参考:数据结构--图 的JAVA实现(上))。并根据FileUtil.java中得到的字符串构造图。
构造 图之后,topoSort方法实现了拓扑排序。
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;/** 用来实现拓扑排序的有向无环图*/
public class DirectedGraph {private class Vertex{private String vertexLabel;// 顶点标识private List<Edge> adjEdges;private int inDegree;// 该顶点的入度public Vertex(String verTtexLabel) {this.vertexLabel = verTtexLabel;inDegree = 0;adjEdges = new LinkedList<Edge>();}}private class Edge {private Vertex endVertex;// private double weight;public Edge(Vertex endVertex) {this.endVertex = endVertex;}}private Map<String, Vertex> directedGraph;public DirectedGraph(String graphContent) {directedGraph = new LinkedHashMap<String, DirectedGraph.Vertex>();buildGraph(graphContent);}private void buildGraph(String graphContent) {String[] lines = graphContent.split("\n");Vertex startNode, endNode;String startNodeLabel, endNodeLabel;Edge e;for (int i = 0; i < lines.length; i++) {String[] nodesInfo = lines[i].split(",");startNodeLabel = nodesInfo[1];endNodeLabel = nodesInfo[2];startNode = directedGraph.get(startNodeLabel);if(startNode == null){startNode = new Vertex(startNodeLabel);directedGraph.put(startNodeLabel, startNode);}endNode = directedGraph.get(endNodeLabel);if(endNode == null){endNode = new Vertex(endNodeLabel);directedGraph.put(endNodeLabel, endNode);}e = new Edge(endNode);//每读入一行代表一条边startNode.adjEdges.add(e);//每读入一行数据,起始顶点添加一条边endNode.inDegree++;//每读入一行数据,终止顶点入度加1}}public void topoSort() throws Exception{int count = 0;Queue<Vertex> queue = new LinkedList<>();// 拓扑排序中用到的栈,也可用队列.//扫描所有的顶点,将入度为0的顶点入队列Collection<Vertex> vertexs = directedGraph.values();for (Vertex vertex : vertexs)if(vertex.inDegree == 0)queue.offer(vertex);while(!queue.isEmpty()){Vertex v = queue.poll();System.out.print(v.vertexLabel + " ");count++;for (Edge e : v.adjEdges)if(--e.endVertex.inDegree == 0)queue.offer(e.endVertex);}if(count != directedGraph.size())throw new Exception("Graph has circle");}
}
FileUtil.java负责从文件中读取图的信息。将文件内容转换成 第一点 中描述的字符串格式。--该类来源于网络
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;public final class FileUtil
{/** * 读取文件并按行输出* @param filePath* @param spec 允许解析的最大行数, spec==null时,解析所有行* @return* @author* @since 2016-3-1*/public static String read(final String filePath, final Integer spec){File file = new File(filePath);// 当文件不存在或者不可读时if ((!isFileExists(file)) || (!file.canRead())){System.out.println("file [" + filePath + "] is not exist or cannot read!!!");return null;}BufferedReader br = null;FileReader fb = null;StringBuffer sb = new StringBuffer();try{fb = new FileReader(file);br = new BufferedReader(fb);String str = null;int index = 0;while (((spec == null) || index++ < spec) && (str = br.readLine()) != null){sb.append(str + "\n");
// System.out.println(str);}}catch (IOException e){e.printStackTrace();}finally{closeQuietly(br);closeQuietly(fb);}return sb.toString();}/** * 写文件* @param filePath 输出文件路径* @param content 要写入的内容* @param append 是否追加* @return* @author s00274007* @since 2016-3-1*/public static int write(final String filePath, final String content, final boolean append){File file = new File(filePath);if (content == null){System.out.println("file [" + filePath + "] invalid!!!");return 0;}// 当文件存在但不可写时if (isFileExists(file) && (!file.canRead())){return 0;}FileWriter fw = null;BufferedWriter bw = null;try{if (!isFileExists(file)){file.createNewFile();}fw = new FileWriter(file, append);bw = new BufferedWriter(fw);bw.write(content);}catch (IOException e){e.printStackTrace();return 0;}finally{closeQuietly(bw);closeQuietly(fw);}return 1;}private static void closeQuietly(Closeable closeable){try{if (closeable != null){closeable.close();}}catch (IOException e){}}private static boolean isFileExists(final File file){if (file.exists() && file.isFile()){return true;}return false;}
}
测试类:TestTopoSort.java
public class TestTopoSort {public static void main(String[] args) {String graphFilePath;if(args.length == 0)graphFilePath = "F:\\xxx";elsegraphFilePath = args[0];String graphContent = FileUtil.read(graphFilePath, null);//从文件中读取图的数据DirectedGraph directedGraph = new DirectedGraph(graphContent);try{directedGraph.topoSort();}catch(Exception e){System.out.println("graph has circle");e.printStackTrace();}}
}
以上内容为参照多个大佬的博客整合后的内容,主要代码部分为 https://www.cnblogs.com/hapjin/p/5432996.html
其余纯手打,有错误请指出,感谢