zoukankan      html  css  js  c++  java
  • 【leetcode】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.

    解题思路:如果某一种输入课程无法被安排,那么一定存在至少这样一门课:通过BFS/DFS的方法从这门课开始,依次遍历需要安排在这门课后面的其他课,最终还会回到这门课,即组成了一个环。我们只有遍历所有的课,看看有没有哪门课会形成环路即可。

    代码如下:

    class Solution(object):
        def canFinish(self, numCourses, prerequisites):
            """
            :type numCourses: int
            :type prerequisites: List[List[int]]
            :rtype: bool
            """
            dic = {}
            for cou,pre in prerequisites:
                if pre not in dic:
                    dic[pre] = [cou]
                else:
                    dic[pre].append(cou)
    
            for i in range(numCourses):
                visit = [0] * numCourses
                queue = [i]
                start = None
                while len(queue) > 0:
                    inx = queue.pop(0)
                    if start == None:
                        start = inx
                    elif inx == start:
                        return False
                    if visit[inx] == 1:
                        continue
                    visit[inx] = 1
                    if inx in dic and len(dic[inx]) > 0:
                        queue += dic[inx]
            return True
  • 相关阅读:
    hdu 1895 Sum Zero hash
    hdu 4277 USACO ORZ dfs+hash
    hdu 6010 Daylight Saving Time 泰勒公式
    Codeforces Round #FF (Div. 2) D. DZY Loves Modification 优先队列
    Codeforces Round #113 (Div. 2) B. Polygons Andrew求凸包
    poj 3304 Segments 线段与直线相交
    gym 101081 gym F. Auction of Services 最小生成树+倍增LCA
    hdu 1558 Segment set 线段相交+并查集
    gym 101081 E. Polish Fortress 几何
    SPOJ
  • 原文地址:https://www.cnblogs.com/seyjs/p/10456295.html
Copyright © 2011-2022 走看看