[leetcode] 207. Course Schedule _ Algorithm Problem Solve for python



1. Problem

207. Course Schedule

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise, return false.

Example 1:

Input: numCourses = 2, prerequisites = [[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: numCourses = 2, prerequisites = [[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.

Constraints:

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • All the pairs prerequisites[i] are unique.

2. Solution

I solved this problem like this.

  • This problem is related to topological sorting.
  • Check nodes adj node. I used dictionary.
  • Check nodes indegree. I used list.
  • Check nodes that each node’s indegree is 0. I put all 0 indegree nodes on deque.
  • While deque is empty, pop node and renew is_visited.
  • Check that node’s adj and decrease the indegree value by 1.
  • If sum(is_visited) == numCourses means that i can visit all nodes, that means there is no cycle.
class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        adj = {}
        indegree = [0] * numCourses
        is_visited = [0] * numCourses
        for second, first in prerequisites:
            indegree[second] += 1
            if first not in adj:
                adj[first] = []
            adj[first].append(second)

        node_list = [i for i, x in enumerate(indegree) if x == 0]
        node_list = deque(node_list)
        while node_list:
            node = node_list.popleft()
            if is_visited[node]:
                continue
            is_visited[node] = 1

            if node not in adj:
                continue
            
            for next_node in adj[node]:
                indegree[next_node] -= 1
                if indegree[next_node] == 0:
                    node_list.append(next_node)

        return sum(is_visited) == numCourses