码迷,mamicode.com
首页 > 其他好文 > 详细

207. Course Schedule

时间:2019-11-19 13:47:00      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:computer   cad   more   dup   tput   ==   pre   can   his   

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 1:

Input: 2, [[1,0]] 
Output: true
Explanation: There are a total of 2 courses to take. 
             To take course 1 you should have finished course 0. So it is possible.

Example 2:

Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take. 
             To take course 1 you should have finished course 0, and to take course 0 you should
             also have finished course 1. So it is impossible.

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.

回顾一下拓扑排序 https://blog.csdn.net/zizi0092011/article/details/85847670 专治有依赖关系的问题

public class Solution {
    public boolean canFinish(int n, int[][] prerequisites) {
        ArrayList<Integer>[] G = new ArrayList[n];
        int[] degree = new int[n];
        ArrayList<Integer> bfs = new ArrayList();
        for (int i = 0; i < n; ++i) G[i] = new ArrayList<Integer>();
        for (int[] e : prerequisites) {
            G[e[1]].add(e[0]);
            degree[e[0]]++;
        }
        for (int i = 0; i < n; ++i) if (degree[i] == 0) bfs.add(i);
        for (int i = 0; i < bfs.size(); ++i)
            for (int j: G[bfs.get(i)])
                if (--degree[j] == 0) bfs.add(j);
        return bfs.size() == n;
    }
}

holy shit this is fucking wubba lubba dub dub.

G存放图,每个点以及它指向的点,degree存放每个点的degree,bfs存放degree为0的点

首先创造图根据prerequisite数组,while记录degree

然后遍历bfs数组,拿出每个点对应的点,--degree,如果是0就加入到bfs中。

正常情况下以bfs.size()作为判断条件会陷入死循环,但加入判断条件后最终也会走到尽头。

207. Course Schedule

标签:computer   cad   more   dup   tput   ==   pre   can   his   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11888631.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!