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.
     

    Approach #2: C++. [graph + dfs]

    class Solution {
    public:
        bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
            // states: 0: not visit     1: visiting     2: visited
            vector<int> node(numCourses, 0);
            graph = vector<vector<int>>(numCourses);
            
            for (auto prerequisite : prerequisites) {
                graph[prerequisite.second].push_back(prerequisite.first);
            }
            
            for (int i = 0; i < numCourses; ++i) {
                if (dfs(node, i)) return false;
            }
            
            return true;
        }
    private:
        vector<vector<int>> graph;
        
        bool dfs(vector<int>& node, int cur) {
            if (node[cur] == 1) return true;
            if (node[cur] == 2) return false;
            
            node[cur] = 1;
            
            for (auto k : graph[cur]) {
                if (dfs(node, k)) return true;
            }
            
            node[cur] = 2;
            return false;
        }
    };
    

      

    Approach #2: Java. [BFS]

    class Solution {
        public boolean canFinish(int numCourses, int[][] prerequisites) {
            ArrayList[] graph = new ArrayList[numCourses];
            int[] degree = new int[numCourses];
            Queue queue = new LinkedList();
            int count = 0;
            
            for (int i = 0; i < numCourses; ++i) {
                graph[i] = new ArrayList();
            }
            
            for (int i = 0; i < prerequisites.length; ++i) {
                degree[prerequisites[i][1]]++;
                graph[prerequisites[i][0]].add(prerequisites[i][1]);
            }
            
            for (int i = 0; i < degree.length; ++i) {
                if (degree[i] == 0) {
                    queue.add(i);
                    count++;
                }
            }
            
            while (queue.size() != 0) {
                int course = (int)queue.poll();
                for (int i = 0; i < graph[course].size(); ++i) {
                    int pointer = (int)graph[course].get(i);
                    degree[pointer]--;
                    if (degree[pointer] == 0) {
                        queue.add(pointer);
                        count++;
                    }
                }
            }
            
            if (count == numCourses) return true;
            else return false;
        }
    }
    

      

    Approach #3: Python.

    class Solution(object):
        def canFinish(self, n, pres):
            """
            :type numCourses: int
            :type prerequisites: List[List[int]]
            :rtype: bool
            """
            from collections import deque
            ind = [[] for _ in xrange(n)]
            oud = [0] * n
            for p in pres:
                oud[p[0]] += 1
                ind[p[1]].append(p[0])
            dq = deque()
            
            for i in xrange(n):
                if oud[i] == 0:
                    dq.append(i)
            
            k = 0
            
            while dq:
                x = dq.popleft()
                k += 1
                for i in ind[x]:
                    oud[i] -= 1
                    if oud[i] == 0:
                        dq.append(i)
                        
            return k == n
    

      

    Analysis:

    At the first, we initialize each node with 0(the state represent that this node haven't visited). and we use a two-dimensional vector to store the linked node. graph[a].push_back(b) represent that a is the prerequisites of b.

    for every number from 0 to n-1 it will have some (or not) prerequisites int the vector of graph[i]. We travel the elements in graph[i] if there is a node which is visiting (which node state is 2), so we can know there is a circle and it will return false in the answer.

    In the processing, If the node equal to 1(which reperesent this node has been visited, in other word it's prerequisites has been satisfied).

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    java表格的使用 单元格绘制二
    Java表格的简单使用一
    Servlet接口五种方法介绍
    C# 图片识别
    asp.net 使用rabbitmq事例
    Windows下安装使用python的Flask框架
    python中闭包的理解
    sql中遍历字符串
    asp.net mvc easyui tree
    c# Castle Windsor简单例子
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10116574.html
Copyright © 2011-2022 走看看