zoukankan      html  css  js  c++  java
  • 拓扑排序

        拓扑排序,首先它是一种排序。不过是应用在有向无环图上,将图的结点按照某种规则排成一个线性队列。只不过排序的规则是

    对于任意两个结点(u,v),如果他们之间存在边(u->v),那么u必须出现在v之前。

              满足拓扑排序的一个有向无环图

    那么按照上面的规则我们可以这样实现拓扑排序

    1: 找到所有初始入度为0的节点,并将它们放入队列或者栈中,并记录此时入度为0的数目。

    2:遍历队列中的结点,对每一个结点,遍历它的直接相连的结点。并将它们入度减一,如果入度为0,将该节点放入队列,更新入度为0的数目(+1)。

    3:重复2中操作,直到队列中元素为空,此时比较入度为0的数目和图的总结点数是否相等。如果相等,则可以满足拓扑排序(也就是判断图不存在环),反之不满足。

    import java.util.Stack;
    
    /**
     * 为了简单起见 使用了邻接矩阵
     * sort具体过程如上述所说
     */
    public class TopoSort {
        public static boolean sort(int[][] matrix, int[] degree) {
            Stack<Integer> stack = new Stack();
            int count = 0;
            for (int i = 0; i < degree.length; i++) {
                if (degree[i] == 0) {
                    stack.push(i);
                    count++;
                }
            }
            while (!stack.isEmpty()) {
                int temp = stack.pop();
                for (int i = 0; i < matrix[temp].length; i++) {
                    if (matrix[temp][i] == 1) {
                        degree[i]--;
                        if (degree[i] == 0) {
                            stack.push(i);
                            count++;
                        }
                    }
                }
            }
            return count == matrix.length;
        }
    
        public static void main(String[] args) {
            int[][] matrix = {{0, 1, 1, 0, 0},
                    {0, 0, 1, 1, 0},
                    {0, 0, 0, 1, 1},
                    {0, 0, 1, 0, 1},
                    {0, 0, 0, 0, 0}};
            int[] degree = {0, 1, 3, 2, 2};
            System.out.println(sort(matrix,degree));
        }
    }
    

      

  • 相关阅读:
    11. Container With Most Water
    9. Palindrome Number
    375. 猜数字大小 II leetcode java
    leetcode 72 编辑距离 JAVA
    73. 矩阵置零 leetcode JAVA
    快速排序 JAVA实现
    63. 不同路径 II leetcode JAVA
    重写(override)与重载(overload)
    62 不同路径 leetcode JAVA
    leetcode 56 合并区间 JAVA
  • 原文地址:https://www.cnblogs.com/shaomys/p/11802650.html
Copyright © 2011-2022 走看看