Skip to content

Commit c2c023e

Browse files
committed
Matrix-Graphs -easy- basic flood fill algorithm implementation
1 parent d9dc239 commit c2c023e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

matrix/easy/flood_fill.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
6+
7+
rows = len(image)
8+
cols = len(image[0])
9+
visited = []
10+
for i in range(rows):
11+
visited.append([0] * cols)
12+
13+
def flood_fill(x, y, new_color, start_color):
14+
visited[x][y] = 1
15+
image[x][y] = new_color
16+
coordinates = [(-1, 0), (0, 1), (1, 0), (0, -1)]
17+
for dx, dy in coordinates:
18+
new_x = x + dx
19+
new_y = y + dy
20+
if 0 <= new_x < rows and 0 <= new_y < cols:
21+
if image[new_x][new_y] == start_color and visited[new_x][new_y] == 0:
22+
flood_fill(new_x, new_y, new_color, start_color)
23+
24+
x, y = sr, sc
25+
start_color = image[x][y]
26+
flood_fill(x, y, newColor, start_color)
27+
return image

0 commit comments

Comments
 (0)