From 8d52aa843fc6ffdd3158aebaabb7764713ce9565 Mon Sep 17 00:00:00 2001 From: pranjay01 Date: Mon, 23 Mar 2026 22:46:04 -0700 Subject: [PATCH] DFS-1 Done --- Problem1.py | 30 ++++++++++++++++++++++ Problem2.py | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 Problem1.py create mode 100644 Problem2.py diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..48a06d1d --- /dev/null +++ b/Problem1.py @@ -0,0 +1,30 @@ +#Flood Fill + +# Time -> O(mXn) +# Space -> O(mXn) -> Stack space +# Logic -> On the + +class Solution: + def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]: + + oldColor = image[sr][sc] + newColor = color + if oldColor == newColor: + return image + + dirs = [(-1,0), (0,1), (1,0), (0,-1)] + + self.dfs(image, sr, sc, oldColor, newColor, dirs) + + return image + + def dfs(self, image, i, j, oldColor, newColor, dirs): + + if i<0 or j< 0 or i==len(image) or j==len(image[0]) or image[i][j]!=oldColor: + return + + image[i][j] = newColor + for r, c in dirs: + self.dfs(image, r+i, c+j, oldColor, newColor, dirs) + + return \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..35e554b0 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,71 @@ +# 01 Matrix + +class Solution: + def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: + rows = len(mat) + columns = len(mat[0]) + + result = [[0 for j in range(columns)] for i in range(rows)] + + for i in range(rows): + for j in range(columns): + if mat[i][j] == 1: + result[i][j] = self.dfs(mat, result, i, j) + + + return result + + + def dfs(self, mat, res, row, column): + + #base case + + #top + if row>0 and mat[row-1][column] == 0: + return 1 + #right + if column<(len(mat[0])-1) and mat[row][column+1] == 0: + return 1 + #bottom + if row0 and mat[row][column-1] == 0: + return 1 + + top = 10001 + right = 10001 + bottom = 10001 + left = 10001 + + #top + if row>0 and res[row-1][column] != 0: + top = res[row-1][column] + + if column>0 and res[row][column-1] != 0: + left = res[row][column-1] + + if column<(len(mat[0])-1): + if res[row][column+1] == 0: + res[row][column+1] = self.dfs(mat, res, row, column+1) + right = res[row][column+1] + + if row