Course Schedule I&II

Course Schedule

这题的本质就是,给你一个代表 graph 的 adjacency array,判断 graph 是否有环。其实和 Graph Valid Tree 非常像。
DFS 找环性能优异,DFS找环相当于在DFS的基础上(1)需要传一个visited数组,每次访问某个点的时候判断该点的visit数值,如果为0表示没有被访问过,1表示有环,2表示访问完成。再次访问1肯定有环。
(2)每次传一个cur参数,表明你现在正在遍历哪个点。
(2)加上一个boolean返回值的helper函数,当遇见环的时候直接返回。
(3)找环属于preorder。
public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        ArrayList[] graph = new ArrayList[numCourses];
        int[] visited = new int[numCourses];


        for(int i = 0; i < numCourses; i++){
            graph[i] = new ArrayList<Integer>();
        }


        for(int[] num : prerequisites){
            int parent = num[1];
            int child = num[0];
            graph[parent].add(child);
        }


        for(int i = 0; i < numCourses; i++){
            if(visited[i] == 0 && hasCycle(i, visited, graph)) return false;
        }


        return true;
    }


    private boolean hasCycle(int cur, int[] visited, ArrayList[] graph){
        visited[cur] = 1;


        boolean hasCycle = false;


        for(int i = 0; i < graph[cur].size(); i++){
            int next = (int) graph[cur].get(i);
            if(visited[next] == 1) return true;
            else if(visited[next] == 0){
                hasCycle = hasCycle || hasCycle(next, visited, graph);
            }
        }


        visited[cur] = 2;


        return hasCycle;
    }
}

BFS 写法,速度超过 82.34%

思路上承接了原来的 topological sort BFS 解法
(1) 建 array 保存所有节点的 indegree
(2) 用ArrayList[]存储graph
在 BFS 时只有 indegree = 0 时才会被加入队列,如果 graph 中有环,会出现有环的部分永远无法进入 BFS 被访问的情况,因此在结尾我们只需要看一下到底有没有点从来没被访问过即可(设置一个counter,看counter ?= number of nodes

Course Schedule II

超过 80.69%,速度尚可~

思路和上一题完全一样,只不过留了个 index 用于记录拓扑顺序。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值