LeetCode207: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.

LeetCode:链接

对于每一对课程的顺序关系,把它看做是一个有向边,边是由两个端点组成的,用两个点来表示边,所有的课程关系即构成一个有向图,问题相当于判断有向图中是否有环。判断有向图是否有环的方法是拓扑排序

拓扑排序:维护一张表记录所有点的入度,移出入度为0的点并更新其他点的入度,重复此过程直到没有点的入度为0。如果原有向图有环的话,此时会有剩余的点且其入度不为0;否则没有剩余的点。

图的拓扑排序可以DFS或者BFS。遍历所有边,计算点的入度;将入度为0的点移出点集,并更新剩余点的入度;重复步骤2,直至没有剩余点或剩余点的入度均大于0。

import collections
class Solution(object):
    def canFinish(self, N, prerequisites):
        """
        :type N,: int
        :type prerequisites: List[List[int]]
        :rtype: bool
        """
        # 记录图的位置关系
        graph = collections.defaultdict(list)
        # 记录图上节点的度
        indegrees = collections.defaultdict(int)
        for u, v in prerequisites:
            graph[v].append(u)
            indegrees[u] += 1
        # 正常取点N次
        for i in range(N):
            zeroDegree = False
            for j in range(N):
                # 每次都找一个入度为0的点
                if indegrees[j] == 0:
                    zeroDegree = True
                    break
            if not zeroDegree: 
                return False
            # 把它的入度变为-1
            indegrees[j] = -1
            # 把从这个点指向的点的入度都-1
            for node in graph[j]:
                indegrees[node] -= 1
        return True         

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/86346831