Some problems about Topological Sort

Topological sort is an basic topic in graph theory, which is the foundation for many other problems like calculating strongly connected components (SCC). This article will discuss a couple of problems related to topological sort and its application. I will keep updating this article to include more problems in the future.

Leetcode 207. Course Schedule
Leetcode 269. Alien Dictionary
\newline
\newline
\newline

Leetcode 207. Course Schedule

This problem is a simple application for topological sort. Each course can be treated as a graph node and prerequisites can be treated as edges. There are two popular way of implementing topological sort, DFS based and BFS based implementations. I will have a discussion about their details.

The following is the DFS based implementation

// DFS based algorithm
class Solution {
   
    //private int idx;
    //private int[] toposort;
    
    public boolean canFinish(int numCourses, int[][] prerequisites) {
   
    	/**
    	 * Use an arry of Set is convenient if the nodes are continuous numbers.
    	 * If the node is a string or other thing, we can also use a Map<String, Set<String>>
    	 */
        Set<Integer>[] g = new Set[numCourses];
        for (int[] edge : prerequisites) {
   
            if (g[edge[1]] == null) {
   
                g[edge[1]] = new HashSet<Integer>();
            }
            g[edge[1]].add(edge[0]);
        }
        //toposort = new int[numCourses];
        //idx = toposort.length - 1;
        int[] state = new int[numCourses];
        for (int i = 0; i < numCourses; ++i) {
   
            if (state[i] == 0 && !dfs(i, state, g)) {
   
                return false;
            }
        }
        return true;
    }
    
    /**
     * There are three states here:
     * 0 means the node is not visited yet.
     * 1 means the node is currently in use, in other words, it is currently on
     * the recursion stack. If the neighbor nodes have edges pointing to nodes in recursion statck,
     * then that produces a cycle.
     * 2 means the node have finished visiting all of its neighbor nodes.
     */
    private boolean dfs(int u, int[] state, Set<Integer> g[]) {
   
        state[u] = 1;
        if (g[u] != null) {
   
            for (
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aliengod

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值