From b607e5e1f8e1df06eb6e402c919af712b41502a5 Mon Sep 17 00:00:00 2001 From: pratikb0501 Date: Sun, 10 May 2026 20:44:25 -0700 Subject: [PATCH] completed bfs-2-1 --- Problem_1.py | 35 +++++++++++++++++++++++++++++++++++ Problem_2.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 Problem_1.py create mode 100644 Problem_2.py diff --git a/Problem_1.py b/Problem_1.py new file mode 100644 index 0000000..5adee3a --- /dev/null +++ b/Problem_1.py @@ -0,0 +1,35 @@ +from collections import deque + + +class Solution: + def orangesRotting(self, grid): + neighbours = [[1, 0], [-1, 0], [0, 1], [0, -1]] + rows, cols = len(grid), len(grid[0]) + q = deque() + fresh = 0 + for r in range(rows): + for c in range(cols): + curr = grid[r][c] + if curr == 2: + q.append((r, c)) + elif curr == 1: + fresh += 1 + if fresh == 0: + return 0 + time = 0 + while q: + qs = len(q) + for _ in range(qs): + cr, cc = q.popleft() + for x, y in neighbours: + nr, nc = cr + x, cc + y + if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1: + fresh -= 1 + grid[nr][nc] = 2 + q.append((nr, nc)) + if fresh == 0: + return time + 1 + time += 1 + if fresh > 0: + return -1 + return time - 1 diff --git a/Problem_2.py b/Problem_2.py new file mode 100644 index 0000000..c91ac01 --- /dev/null +++ b/Problem_2.py @@ -0,0 +1,42 @@ +""" +# Definition for Employee. +class Employee: + def __init__(self, id: int, importance: int, subordinates: List[int]): + self.id = id + self.importance = importance + self.subordinates = subordinates +""" + + +from collections import deque + + +class Solution: + def getImportance(self, employees, id): + adj = {} + importance = {} + for employee in employees: + eid, imp, subs = employee.id, employee.importance, employee.subordinates + importance[eid] = imp + for s in subs: + if eid in adj: + adj[eid].append(s) + else: + adj[eid] = [s] + print(adj) + q = deque() + result = importance[id] + + if id not in adj: + return result + for s in adj[id]: + q.append(s) + while q: + front = q.popleft() + result += importance[front] + if front not in adj: + continue + for neigh in adj[front]: + q.append(neigh) + + return result