Suppose there are a total of numCourses courses we have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 we have to first take course 1, which is expressed using a pair: [0,1]. Suppose there are total number of courses that is provided and a list of prerequisite pairs, we have to check whether is it possible for you to finish all courses?
So if the input is like − numCourses = 2 and prerequisites = [[1, 0]], then the result will be true, because there are a total of 2 courses to take. To take course 1 we should have finished course 0. So it is possible.
To solve this, we will follow these steps −
In the main method, it will take numCourses, and prerequisites: This will act like −
if prerequisites has no entry, then return true
make an array called visited, fill this with 0, and its range is same as numCourses
adj_list := create a graph using prerequisites
for i in range 0 to numCourses
if visited[i] is false, then
if there is no cycle among the visited node in the graph, return false
return true
Example
Let us see the following implementation to get a better understanding −
class Solution(object): def canFinish(self, numCourses, prerequisites): if len(prerequisites) == 0: return True visited = [0 for i in range(numCourses)] adj_list = self.make_graph(prerequisites) for i in range(numCourses): if not visited[i]: if not self.cycle(adj_list,visited,i): return False return True def cycle(self,adj_list,visited,current_node = 0): if visited[current_node] ==-1: return False if visited[current_node] == 1: return True visited[current_node] = -1 if(current_node in adj_list): for i in adj_list[current_node]: if not self.cycle(adj_list,visited,i): return False visited[current_node] = 1 return True def make_graph(self,array): adj_list = {} for i in array: if i[1] in adj_list: adj_list[i[1]].append(i[0]) else: adj_list[i[1]] = [i[0]] return adj_list ob = Solution() print(ob.canFinish(2, [[1,0]]))
Input
2 [[1,0]]
Output
true