LeetCode 207. Course Schedule--有向圖找環--面試算法題--DFS遞歸,拓撲排序迭代--Python

此文首發於我的個人博客:LeetCode 207. Course Schedule–有向圖找環–面試算法題–DFS遞歸,拓撲排序迭代–Python — zhang0peter的個人博客


LeetCode題解文章分類:LeetCode題解文章集合
LeetCode 所有題目總結:LeetCode 所有題目總結


題目地址:Course Schedule - LeetCode


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:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.


這道題目是我在XX公司面試時遇到的算法題,當時就看出來這是判斷有向圖(DAG)是否存在環。
一時想不起算法,於是就自己實現了一個時間複雜度爲O(V^2)的算法,面試官自然不滿意,於是當時現場又用遞歸的做法實現了時間複雜度爲O(N+V)的算法(dfs),這個做法只是口述了一遍,並沒有真的實現。現在想想實現起來還是非常複雜的。

剛剛我實現了O(V^2)的算法,發現算法有bug,尷尬了。
然後實現自己的DFS算法,花了至少20分鐘,現場做肯定做不出來。

DFS-Python解法如下:

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        s = {}
        res = set()
        flag = 0

        def helper(begin=-1, find=set()):
            nonlocal flag, res, s
            for i in s[begin]:
                if i not in res:
                    if i in find:
                        flag = 1
                        return
                    find.add(i)
                    helper(i, find=find)
            res.add(begin)

        for i in range(0, numCourses):
            s[i] = set()
        for i in prerequisites:
            s[i[0]].add(i[1])
        for i in range(0, numCourses):
            helper(begin=i, find={i})
            if flag == 1:
                return False
        return True

代碼不好,別人寫的優化過的代碼如下:

class Solution(object):
    def canFinish(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: bool
        """
        graph = [[] for _ in range(numCourses)]
        visited = [0 for _ in range(numCourses)]
        # create graph
        for pair in prerequisites:
            x, y = pair
            graph[x].append(y)
        # visit each node
        for i in range(numCourses):
            if not self.dfs(graph, visited, i):
                return False
        return True
    
    def dfs(self, graph, visited, i):
        # if ith node is marked as being visited, then a cycle is found
        if visited[i] == -1:
            return False
        # if it is done visted, then do not visit again
        if visited[i] == 1:
            return True
        # mark as being visited
        visited[i] = -1
        # visit all the neighbours
        for j in graph[i]:
            if not self.dfs(graph, visited, j):
                return False
        # after visit all the neighbours, mark it as done visited
        visited[i] = 1
        return True

隨後看到另外一位大佬用OOP的思想重寫了代碼,雖然速度沒有提升,但思路清晰多了:

class Solution:
    class Course(object):
        def __init__(self):
            self.being_visit, self.visit_done = False, False
            self.pre_course = []

        def is_cyclic(self):
            if self.visit_done is True:
                return False
            if self.being_visit is True:
                return True
            self.being_visit = True
            for course in self.pre_course:
                if course.is_cyclic():
                    return True
            self.being_visit = False
            self.visit_done = True
            return False

    def canFinish(self, num_courses, prerequisites) -> bool:
        l = [self.Course() for _ in range(0, num_courses)]
        for (course1, course2) in prerequisites:
            l[course1].pre_course.append(l[course2])
        for i in range(0, num_courses):
            if l[i].is_cyclic():
                return False
        return True

標準的更正式更快的解法是拓撲排序(Topological Sorting),可以參考:Kahn’s algorithm for Topological Sorting - GeeksforGeeks

class Solution:
    def canFinish(self, num_courses, prerequisites) -> bool:
        vertices = num_courses
        adj_list = [[] for _ in range(0, vertices)]
        in_degree = [0 for _ in range(0, vertices)]
        for (course1, course2) in prerequisites:
            adj_list[course1].append(course2)
            in_degree[course2] += 1
        q = [i for i in range(0, vertices) if in_degree[i] == 0]
        count = 0
        while q:
            front = q.pop(0)
            for i in adj_list[front]:
                in_degree[i] -= 1
                if in_degree[i] < 0:
                    return False
                elif in_degree[i] == 0:
                    q.append(i)
            count += 1
        if count == vertices:
            return True
        else:
            return False
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章