Skip to content

Commit 53c05ac

Browse files
authored
Create Flood Fill
1 parent a71618f commit 53c05ac

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

matrix/Flood Fill

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from typing import List
2+
3+
class Solution:
4+
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
5+
rows, cols = len(image), len(image[0])
6+
original_color = image[sr][sc]
7+
8+
# If the starting pixel already has the target color, return image as is
9+
if original_color == color:
10+
return image
11+
12+
def dfs(r, c):
13+
# Base case: stop if out of bounds or not the same original color
14+
if r < 0 or r >= rows or c < 0 or c >= cols:
15+
return
16+
if image[r][c] != original_color:
17+
return
18+
19+
# Recolor current pixel
20+
image[r][c] = color
21+
22+
# Visit 4 neighbors (up, down, left, right)
23+
dfs(r+1, c)
24+
dfs(r-1, c)
25+
dfs(r, c+1)
26+
dfs(r, c-1)
27+
28+
dfs(sr, sc)
29+
return image

0 commit comments

Comments
 (0)