Skip to content
Open

DFS-1 #1410

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 01matrix.py
Original file line number Diff line number Diff line change
@@ -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
33 changes: 33 additions & 0 deletions floodfill.py
Original file line number Diff line number Diff line change
@@ -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