-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfloodFill.js
46 lines (35 loc) · 897 Bytes
/
floodFill.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
40
41
42
43
44
45
46
/**
* @param {number[][]} image
* @param {number} sr
* @param {number} sc
* @param {number} newColor
* @return {number[][]}
*/
const floodFill = function (image, sr, sc, newColor) {
const startColor = image[sr][sc]
if (startColor === newColor) {
return image
}
const queue = [[sr, sc]]
while (queue.length > 0) {
const [row, col] = queue.shift()
if (image[row][col] === newColor) {
continue
}
image[row][col] = newColor
if (image[row - 1] && image[row - 1][col] === startColor) {
queue.push([row - 1, col])
}
if (image[row + 1] && image[row + 1][col] === startColor) {
queue.push([row + 1, col])
}
if (image[row][col - 1] === startColor) {
queue.push([row, col - 1])
}
if (image[row][col + 1] === startColor) {
queue.push([row, col + 1])
}
}
return image
}
module.exports = floodFill