Skip to content
Open

done #1386

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
37 changes: 37 additions & 0 deletions problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""
I used dfs approach to solve this question as it ask us to go deep and then perform action, so keeping the boundary conditions, we change the particular cell into the start tcolor
and move ahead and then follow the same for all 4 directions. This way everything is covered and we can return the final image.
TC is O(m x n) and SC is also O(m x n)
"""

class Solution(object):
def floodFill(self, image, sr, sc, color):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type color: int
:rtype: List[List[int]]
"""
rows, cols = len(image), len(image[0])
start = image[sr][sc]

if start == color:
return image

def dfs(r, c):

if (r < 0 or r >= rows or
c < 0 or c >= cols or
image[r][c] != start):
return

image[r][c] = color

dfs(r - 1, c)
dfs(r, c - 1)
dfs(r + 1, c)
dfs(r, c + 1)

dfs(sr, sc)
return image
35 changes: 35 additions & 0 deletions problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
Instead of performing BFS on the 1, we apply it on 0 and then transform all other into -1, so when all 0 positions are appended to the queue, we explore al 4 directions, and
if we find a -1 and are within bounds, then we take its og value and add one to it as our distance. then again append this to the queue and once all this is done, we ret the image
TC will be O(mxn) and SC will be o(mxn) in worst case
"""


class Solution(object):
def updateMatrix(self, mat):
"""
:type mat: List[List[int]]
:rtype: List[List[int]]
"""
rows, cols = len(mat), len(mat[0])
q = collections.deque()

for r in range(rows):
for c in range(cols):
if mat[r][c] == 0:
q.append((r, c))
else:
mat[r][c] = -1

dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
while q:
r, c = q.popleft()
for dr, dc in dirs:
nr, nc = r + dr, c + dc
if (0 <= nr < rows and
0 <= nc < cols and
mat[nr][nc] == -1):
mat[nr][nc] = mat[r][c] + 1
q.append((nr, nc))
return mat