-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
39 lines (33 loc) · 862 Bytes
/
solution.js
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
38
39
/**
* @param {number[][]} image
* @param {number} sr
* @param {number} sc
* @param {number} newColor
* @return {number[][]}
*/
// DFS
var floodFill = function (image, sr, sc, newColor) {
const color = image[sr][sc];
if (color === newColor) {
return image;
}
const maxX = image.length - 1;
const maxY = image[0].length - 1;
function dfs (image, x, y) {
image[x][y] = newColor;
if (x > 0 && image[x - 1][y] === color) {
dfs(image, x - 1, y);
}
if (y < maxY && image[x][y + 1] === color) {
dfs(image, x, y + 1);
}
if (x < maxX && image[x + 1][y] === color) {
dfs(image, x + 1, y);
}
if (y > 0 && image[x][y - 1] === color) {
dfs(image, x, y - 1);
}
}
dfs(image, sr, sc);
return image;
};