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)

转载于:https://www.cnblogs.com/ireneyanglan/p/4837107.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值