File tree 1 file changed +75
-0
lines changed
1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 1. Cycle Detection (DFS)
2
+
3
+ ``` python
4
+ class Solution :
5
+ def canFinish (self , numCourses : int , prerequisites : List[List[int ]]) -> bool :
6
+ # Map each course to its prerequisites
7
+ preMap = {i: [] for i in range (numCourses)}
8
+ for crs, pre in prerequisites:
9
+ preMap[crs].append(pre)
10
+
11
+ # Store all courses along the current DFS path
12
+ visiting = set ()
13
+
14
+ def dfs (crs ):
15
+ if crs in visiting:
16
+ # Cycle detected
17
+ return False
18
+ if preMap[crs] == []:
19
+ return True
20
+
21
+ visiting.add(crs)
22
+ for pre in preMap[crs]:
23
+ if not dfs(pre):
24
+ return False
25
+ visiting.remove(crs)
26
+ preMap[crs] = []
27
+ return True
28
+
29
+ for c in range (numCourses):
30
+ if not dfs(c):
31
+ return False
32
+ return True
33
+ ```
34
+
35
+ ### Time & Space Complexity
36
+
37
+ * Time complexity: $O(V + E)$
38
+ * Space complexity: $O(V + E)$
39
+
40
+ ---
41
+
42
+ ## 2. Topological Sort (Kahn's Algorithm)
43
+
44
+ ``` python
45
+ class Solution :
46
+ def canFinish (self , numCourses : int , prerequisites : List[List[int ]]) -> bool :
47
+ # Build adjacency list
48
+ indegree = [0 ] * numCourses
49
+ adj = [[] for i in range (numCourses)]
50
+ for src, dst in prerequisites:
51
+ indegree[dst] += 1
52
+ adj[src].append(dst)
53
+
54
+ # Initialize Queue
55
+ q = deque()
56
+ for n in range (numCourses):
57
+ if indegree[n] == 0 :
58
+ q.append(n)
59
+
60
+ # BFS
61
+ while q:
62
+ node = q.popleft()
63
+ for nei in adj[node]:
64
+ indegree[nei] -= 1
65
+ if indegree[nei] == 0 :
66
+ q.append(nei)
67
+
68
+ return sum (indegree) == 0
69
+ ```
70
+
71
+ ### Time & Space Complexity
72
+
73
+ * Time complexity: $O(V + E)$
74
+ * Space complexity: $O(V + E)$
75
+
You can’t perform that action at this time.
0 commit comments