From bea1ee8a3540bb84ce8f22ebe9a3255fa61bd78b Mon Sep 17 00:00:00 2001 From: Shinjanee Gupta Date: Tue, 3 Mar 2026 11:30:30 -0800 Subject: [PATCH] BFS-1 --- CourseSchedule.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ LevelOrder.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 CourseSchedule.py create mode 100644 LevelOrder.py diff --git a/CourseSchedule.py b/CourseSchedule.py new file mode 100644 index 00000000..80e0dddd --- /dev/null +++ b/CourseSchedule.py @@ -0,0 +1,47 @@ +# Time Complexity : O(V+E) +# Space Complexity : O(V+E) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : BFS to perform topological sort by starting with nodes having indegree = 0. +# For each course, reduce the indegree of its dependents and add them to the queue if their indegree becomes 0. +# If we can visit all courses this way, there's no cycle, and the courses can be completed. + + +class Solution: + def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: + indegrees = [0] * numCourses + adjacencyMatrix = {} + + for pr in prerequisites: + indegrees[pr[0]] += 1 + if pr[1] not in adjacencyMatrix: + adjacencyMatrix[pr[1]] = [] + adjacencyMatrix[pr[1]].append(pr[0]) + + count = 0 + q = deque() + + for i in range(numCourses): + if indegrees[i] == 0: + q.append(i) + count += 1 + + if not q: + return False + if count == numCourses: + return True + + while q: + curr = q.popleft() + deps = adjacencyMatrix.get(curr) + if deps: + for dep in deps: + indegrees[dep] -= 1 + if indegrees[dep] == 0: + q.append(dep) + count += 1 + if count == numCourses: + return True + + return False + \ No newline at end of file diff --git a/LevelOrder.py b/LevelOrder.py new file mode 100644 index 00000000..6c3460b5 --- /dev/null +++ b/LevelOrder.py @@ -0,0 +1,38 @@ +# Time Complexity : O(n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : At each step, the size tells how many nodes are at the current level. + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + if root is None: + return [] + + res = [] + q = deque() + q.append(root) + + while q: + size = len(q) + temp = [] + + for i in range(size): + curr = q.popleft() + temp.append(curr.val) + if curr.left: + q.append(curr.left) + if curr.right: + q.append(curr.right) + res.append(temp) + return res + + + + \ No newline at end of file