diff --git a/problem1.py b/problem1.py new file mode 100644 index 00000000..06956a40 --- /dev/null +++ b/problem1.py @@ -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 \ No newline at end of file diff --git a/problem2.py b/problem2.py new file mode 100644 index 00000000..5383b6a3 --- /dev/null +++ b/problem2.py @@ -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 +