Created
August 28, 2022 20:40
-
-
Save louis-e/8bb701318d8f478ed45e04bec52ec01e to your computer and use it in GitHub Desktop.
Fixed version of an already existing floodfill algorithm (https://leetcode.com/problems/flood-fill/discuss/225010/python-flood-fill-bfs-faster-than-9988)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def floodFill(img, sr, sc, new_value): | |
old_value = img[sr][sc][0] | |
queue = [(sr, sc)] | |
seen = set() | |
tot_rows = img.shape[0] | |
tot_cols = img.shape[1] | |
while queue: | |
nxt = [] | |
for x, y in queue: | |
if (img[x][y] == new_value): | |
continue | |
img[x][y] = new_value | |
seen.add((x,y)) | |
if x and (x - 1, y) not in seen and img[x - 1][y] == old_value: | |
nxt.append((x - 1, y)) | |
if y and (x, y- 1) not in seen and img[x][y - 1] == old_value: | |
nxt.append((x, y - 1)) | |
if x < tot_rows - 1 and (x + 1, y) not in seen and img[x + 1][y] == old_value: | |
nxt.append((x + 1, y)) | |
if y < tot_cols - 1 and (x, y + 1) not in seen and img[x][y + 1] == old_value: | |
nxt.append((x, y + 1)) | |
queue = nxt | |
return img |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment