-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
39 lines (35 loc) · 1.15 KB
/
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[][]}
*/
var floodFill = function(image, sr, sc, newColor) {
let filledMap = {},
stack = [[sr, sc]],
color = image[sr][sc]
while (stack.length > 0) {
let point = stack.pop(),
coordinate = `${point[0]}X${point[1]}`
if (filledMap[coordinate] === undefined) {
filledMap[coordinate] = true
} else {
continue
}
if (point[0] >= 1 && image[point[0] - 1][point[1]] === color) {
stack.push([point[0] - 1, point[1]])
}
if (point[0] + 1 < image.length && image[point[0] + 1][point[1]] === color) {
stack.push([point[0] + 1, point[1]])
}
if (point[1] >= 1 && image[point[0]][point[1] - 1] === color) {
stack.push([point[0], point[1] - 1])
}
if (point[1] + 1 < image[0].length && image[point[0]][point[1] + 1] === color) {
stack.push([point[0], point[1] + 1])
}
image[point[0]][point[1]] = newColor
}
return image
};