Skip to content
Open

BFS-1 #1615

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
39 changes: 39 additions & 0 deletions courses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""
time - o(n)
space - o(n)
here we calculate the in degree of all courses and store them in an array, and create a graph where the prereq is key and courses you can complete after prereq are a list of values
we take the courses that have 0 in degree and add them to a queue to do bfs, once we pop a course from the queue we take all its dependents and reduce the in degree in the list
if any indegree is 0, it means it has satisfied all prereqs and can go onto the list. finally all courses popped from the list are tallied and if equal to numcourses we return true
"""
from collections import deque
from typing import List
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:

in_degree = [0]*numCourses
dep_graph = {}
for i in range(len(prerequisites)):
a,b = prerequisites[i]
in_degree[a]+=1
if b not in dep_graph:
dep_graph[b] = []
dep_graph[b].append(a)
q = deque()
for index, val in enumerate(in_degree):
if val==0:
q.append(index)
done_courses = 0
while q:
node = q.popleft()
done_courses+=1
if node in dep_graph:
for course in dep_graph[node]:
in_degree[course]-=1
if in_degree[course]==0:
q.append(course)

return done_courses==numCourses




34 changes: 34 additions & 0 deletions level_traversal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
time = o(n)
space = o(n)
we take the node and add it to a deque, at each instance we take the length of the queue and then pop
those number of elements and add their values to a temp list and add its children back to the queue
we finally add the temp list to a global list and return it
"""
from typing import Optional, List
from collections import deque
# 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 not root:
return []
q = deque()
q.append(root)
result = []
while q:
n = len(q)
level = []
for _ in range(n):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
result.append(level)
return result