zoukankan      html  css  js  c++  java
  • Topological Sorting

    Topological sorting/ ordering is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex vu comes before v in the ordering. We can conduct topological sorting only on DAG (directed acyclic graph). Therefore, topological sorting is often used in scheduling a sequence of jobs or tasks based on their dependencies. Another typical usage is to check whether a graph has circle.

    Here is a more detailed description -> Wiki Topological sorting

    Below are several algorithms to implement topological sorting. Mostly, the time complexity is O(|V| + |E|).

    Algorithm 1 -- Ordinary Way

    Time complexity O(|V|^2 + |E|) In Step 1, time complexity O(|V|) for each vertex.

    1. Identify vertices that have no incoming edge (If no such edges, graph has cycles (cyclic graph))
    2. Select one such vertex
    3. Delete this vertex of in-degree 0 and all its outgoing edges from the graph. Place it in the output.
    4. Repeat Steps 1 to Step 3 until graph is empty

    (referrence: cs.washington Topological Sorting)

    Algorithm 2 -- Queue

    Improve algorithm 1 by use queue to store vertex whose in-degree is 0. Time complex O(|V| + |E|).

    Algorithm 3 -- DFS

    When we conduct DFS on graph, we find that if we order vertices according to its complete time, the result if one topological sorting solution.

    Time complexity O(|V| + |E|)

     1 import java.util.*;
     2 
     3 public class TopologicalSort {
     4 
     5   // When we use iteration to implement DFS, we only need 2 status for each vertex
     6   static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> res, int u) {
     7     used[u] = true;
     8     for (int v : graph[u])
     9       if (!used[v])
    10         dfs(graph, used, res, v);
    11     res.add(u);
    12   }
    13
    14   public static List<Integer> topologicalSort(List<Integer>[] graph) {
    15     int n = graph.length;
    16     boolean[] used = new boolean[n];
    17     List<Integer> res = new ArrayList<>();
    18     for (int i = 0; i < n; i++)
    19       if (!used[i])
    20         dfs(graph, used, res, i);
    21     Collections.reverse(res);
    22     return res;
    23   }
    24 }

    (referrence: DFS: Topological sorting)

  • 相关阅读:
    RS交叉表按照预定的节点成员排序
    Open DJ备份与恢复方案
    SQLServer2008备份时发生无法打开备份设备
    数据仓库备份思路
    SQLServer代理新建或者编辑作业报错
    Transfrom在64bit服务下面无法运行
    ActiveReport开发入门-图表的交互性
    ActiveReport开发入门-列表的交互性
    /etc/fstab 参数详解(转)
    CentOS7 查看硬盘情况
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4837107.html
Copyright © 2011-2022 走看看