-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path733-flood-fill.js
More file actions
53 lines (52 loc) · 1.38 KB
/
733-flood-fill.js
File metadata and controls
53 lines (52 loc) · 1.38 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* @param {number[][]} image
* @param {number} sr
* @param {number} sc
* @param {number} newColor
* @return {number[][]}
*/
var floodFill_DFS = function(image, sr, sc, newColor) {
const oldColor = image[sr][sc]
function dfs(row, col) {
if(row<0 || row>=image.length || col<0 || col>=image[0].length) return
if(image[row][col]!==oldColor) return
image[row][col] = newColor
dfs(row-1, col)
dfs(row+1, col)
dfs(row, col-1)
dfs(row, col+1)
}
if(oldColor===newColor) return image
dfs(sr, sc)
return image
};
var floodFill_BFS = function(image, sr, sc, newColor) {
const getNeighbors = (row, col, color) => {
const above = (row-1) >= 0 ? [row-1, col] : []
const below = (row+1) < image.length ? [row+1, col] : []
const left = (col-1) >= 0 ? [row, col-1] : []
const right = (col+1) < image[0].length ? [row, col+1] : []
return [above, below, left, right].filter(a =>
a.length > 0 && image[a[0]][a[1]] === color
)
}
let oldColor = image[sr][sc]
const toExplore = []
let u = [sr, sc]
let seen = {}
toExplore.push(u)
seen[String(u)] = true
let cs
while(toExplore.length>0) {
u = toExplore.shift()
image[u[0]][u[1]] = newColor
cs = getNeighbors(u[0], u[1], oldColor)
for(let c of cs) {
if(!seen[String(c)]) {
toExplore.push(c)
seen[String(c)] = true
}
}
}
return image
};