zoukankan      html  css  js  c++  java
  • 207. Course Schedule

    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()作为判断条件会陷入死循环,但加入判断条件后最终也会走到尽头。

  • 相关阅读:
    项目Alpha冲刺——总结
    项目Alpha冲刺——集合
    项目Alpha冲刺 10
    项目Alpha冲刺 9
    项目Alpha冲刺 8
    项目Alpha冲刺 7
    Beta冲刺(2/7)——2019.5.23
    Beta冲刺(1/7)——2019.5.22
    项目Beta冲刺(团队) —— 凡事预则立
    Alpha 事后诸葛亮(团队)
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11888631.html
Copyright © 2011-2022 走看看