Skip to content
Open

BFS-1 #1626

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions CourseSchedule.py
Original file line number Diff line number Diff line change
@@ -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

38 changes: 38 additions & 0 deletions LevelOrder.py
Original file line number Diff line number Diff line change
@@ -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