zoukankan      html  css  js  c++  java
  • LN : leetcode 207 Course Schedule

    lc 207 Course Schedule


    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?

    For example:

    2, [[1,0]]
    

    There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

    2, [[1,0],[0,1]]
    

    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.

    DFS Accepted##

    这是一个非常典型的拓扑排序问题,整个问题可以总结为如何判断有向图是否有环。通过对图上的每一个点做DFS,如果都是无环的,则能证明课程安排是合理的。注意,点的状态有三种,分别是没被访问,第一次访问后以及第二次访问后。

    class Solution {
    public:
        bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
            vector<set<int>> graph(numCourses);
            bool cycle = false;
            for (auto prev : prerequisites) {
                graph[prev.second].insert(prev.first);
            }
            vector<int> visited(numCourses, 0);
            for (int i = 0; i < numCourses; i++) {
                if (cycle) return false;
                if (visited[i] == 0) dfs(i, graph, visited, cycle);
            }
            return !cycle;
        }
        
        void dfs(int nodei, vector<set<int>> &graph, vector<int> &visited, bool &cycle) {
            if (visited[nodei] == 1) {
                cycle = true;
                return;
            }
            visited[nodei] = true;
            for (auto i : graph[nodei]) {
                dfs(i, graph, visited, cycle);
                if (cycle) return;
            }
            visited[nodei] = 2;
        }
    };
    
  • 相关阅读:
    历史上的今天:3月1日
    用Windows Live Writer远程更新wordpress博客
    二月只有28天
    办公也可云概念
    FLASH做的画图板
    FLASH鼠标跟随特效
    silverlight应该以什么面孔见人?
    飞信Fetion 开发资料及下载
    收藏一个数学的C++算法的好博客
    下载网站资源共享
  • 原文地址:https://www.cnblogs.com/renleimlj/p/7588525.html
Copyright © 2011-2022 走看看