From f3c25733706de4a2f0b5a8f543c4b3457f710cf4 Mon Sep 17 00:00:00 2001 From: sainaga00 Date: Wed, 8 Apr 2026 22:07:52 -0400 Subject: [PATCH] DFS-1 --- 01matrix.py | 39 +++++++++++++++++++++++++++++++++++++++ floodfill.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 72 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..bc225929 --- /dev/null +++ b/01matrix.py @@ -0,0 +1,39 @@ +# 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 multi-source BFS. +# Initialize queue with all cells having value 0 and set their distance to 0. +# For each cell, explore its 4-directional neighbors. +# If a neighbor is unvisited (distance = -1), update its distance as +# current distance + 1 and push it into the queue. +# This ensures the shortest distance to nearest 0 for all cells. + +from collections import deque +from typing import List + +class Solution: + def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: + rows, cols = len(mat), len(mat[0]) + q = deque() + dist = [[-1] * cols for _ in range(rows)] + + for r in range(rows): + for c in range(cols): + if mat[r][c] == 0: + q.append((r, c)) + dist[r][c] = 0 + + directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] + + while q: + r, c = q.popleft() + + for dr, dc in directions: + nr, nc = r + dr, c + dc + + if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1: + dist[nr][nc] = dist[r][c] + 1 + q.append((nr, nc)) + + return dist \ No newline at end of file diff --git a/floodfill.py b/floodfill.py new file mode 100644 index 00000000..b021cf36 --- /dev/null +++ b/floodfill.py @@ -0,0 +1,33 @@ +# 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 DFS. +# Start from the given cell (sr, sc) and store its original color. +# If the original color is same as new color, return early. +# Recursively visit all 4-directionally connected cells having the same original color. +# Change their color to the new color during traversal. + +class Solution: + def floodFill(self, image, sr, sc, color): + rows, cols = len(image), len(image[0]) + original = image[sr][sc] + + if original == color: + return image + + def dfs(r, c): + if r < 0 or c < 0 or r >= rows or c >= cols: + return + if image[r][c] != original: + return + + image[r][c] = color + + dfs(r+1, c) + dfs(r-1, c) + dfs(r, c+1) + dfs(r, c-1) + + dfs(sr, sc) + return image \ No newline at end of file