-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0733-flood-fill.js
More file actions
37 lines (31 loc) · 1.04 KB
/
0733-flood-fill.js
File metadata and controls
37 lines (31 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Flood Fill
* Time Complexity: O(R * C)
* Space Complexity: O(R * C)
*/
var floodFill = function (image, sr, sc, newColor) {
const gridRowsDimension = image.length;
const gridColsDimension = image[0].length;
const initialPixelValue = image[sr][sc];
if (initialPixelValue === newColor) {
return image;
}
const traverseAndRecolor = (currentRowPosition, currentColPosition) => {
if (
currentRowPosition < 0 ||
currentRowPosition >= gridRowsDimension ||
currentColPosition < 0 ||
currentColPosition >= gridColsDimension ||
image[currentRowPosition][currentColPosition] !== initialPixelValue
) {
return;
}
image[currentRowPosition][currentColPosition] = newColor;
traverseAndRecolor(currentRowPosition + 1, currentColPosition);
traverseAndRecolor(currentRowPosition - 1, currentColPosition);
traverseAndRecolor(currentRowPosition, currentColPosition + 1);
traverseAndRecolor(currentRowPosition, currentColPosition - 1);
};
traverseAndRecolor(sr, sc);
return image;
};