Flood Fill LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} image
3
* @param {number} sr
4
* @param {number} sc
5
* @param {number} color
6
* @return {number[][]}
7
*/
8
var floodFill = function (image, sr, sc, color) {
9
const pixelsToCheck = [[sr, sc]];
10
const startingPixelColor = image[sr][sc];
11
const directions = [
12
[1, 0],
13
[0, 1],
14
[-1, 0],
15
[0, -1],
16
];
17
const seenPixels = new Set();
18

19
if (startingPixelColor === undefined || startingPixelColor === color)
20
return image;
21

22
for (const pixel of pixelsToCheck) {
23
const currentPixelColor = image[pixel[0]]?.[pixel[1]];
24

25
if (
26
currentPixelColor === undefined ||
27
startingPixelColor !== currentPixelColor
28
)
29
continue;
30

31
image[pixel[0]][pixel[1]] = color;
32

33
for (const direction of directions) {
34
const newPixel = [pixel[0] + direction[0], pixel[1] + direction[1]];
35
const pixelString = newPixel.join();
36

37
if (seenPixels.has(pixelString)) continue;
38

39
pixelsToCheck.push(newPixel);
40
seenPixels.add(pixelString);
41
}
42
}
43

44
return image;
45
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0