From 7bccf449877e8028369be1bf3813cbfa8cd6982e Mon Sep 17 00:00:00 2001 From: Shinjanee Gupta Date: Fri, 6 Mar 2026 19:43:05 -0800 Subject: [PATCH] DFS-1 --- 01Matrix.py | 38 ++++++++++++++++++++++++++++++++++++++ FloodFill.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 01Matrix.py create mode 100644 FloodFill.py diff --git a/01Matrix.py b/01Matrix.py new file mode 100644 index 00000000..017df8a9 --- /dev/null +++ b/01Matrix.py @@ -0,0 +1,38 @@ +# Time Complexity : O(m*n) +# Space Complexity : O(m*n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : First, add all 0s to a queue and mark all 1s as -1 to show they haven't been processed yet. +# Then, use BFS from the 0s to expand layer by layer and assign the correct distance to each -1. +# This way, every 1 gets the shortest distance to the nearest 0 as BFS explores in waves. + +class Solution: + def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: + dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]] + rows, cols = len(mat), len(mat[0]) + + q = deque() + + for i in range(rows): + for j in range(cols): + if mat[i][j] == 0: + q.append([i,j]) + else: + mat[i][j] = -1 + + dist = 1 + + while q: + size = len(q) + for _ in range(size): + curr = q.popleft() + for dx, dy in dirs: + r = curr[0] + dx + c = curr[1] + dy + + if 0 <= r < rows and 0 <= c < cols and mat[r][c] == -1: + q.append([r, c]) + mat[r][c] = dist + dist += 1 + + return mat diff --git a/FloodFill.py b/FloodFill.py new file mode 100644 index 00000000..decc87ff --- /dev/null +++ b/FloodFill.py @@ -0,0 +1,31 @@ +# Time Complexity : O(m*n) +# Space Complexity : O(m*n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : Use a queue to visit neighbors with the same old color. +# Each valid neighbor is colored and added to the queue for further expansion. + +class Solution: + def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]: + oldColor = image[sr][sc] + if oldColor == color: + return image + + dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]] + rows, cols = len(image), len(image[0]) + + q = deque() + q.append([sr,sc]) + image[sr][sc] = color + + while q: + curr = q.popleft() + for dx, dy in dirs: + r = curr[0] + dx + c = curr[1] + dy + + if r >= 0 and c >= 0 and r < rows and c < cols and image[r][c] == oldColor: + image[r][c] = color + q.append([r, c]) + + return image \ No newline at end of file