forked from everthis/leetcode-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1034-coloring-a-border.js
49 lines (46 loc) · 1.32 KB
/
1034-coloring-a-border.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
47
48
49
/**
* @param {number[][]} grid
* @param {number} r0
* @param {number} c0
* @param {number} color
* @return {number[][]}
*/
const colorBorder = function(grid, r0, c0, color) {
const dirs = [[-1,0], [1,0], [0,1], [0,-1]]
const c = grid[r0][c0]
const rows = grid.length
const cols = grid[0].length
const visited = Array.from({length: rows}, () => new Array(cols).fill(0))
dfs(r0, c0, c, rows, cols, visited, grid, dirs)
for(let i = 0; i < rows; i++) {
for(let j = 0; j < cols; j++) {
if(visited[i][j] === -1) {
if(i === 0 || j === 0 || i === rows - 1 || j === cols - 1) {
visited[i][j] = -2
} else {
for(let dir of dirs) {
if(visited[i + dir[0]][j + dir[1]] === 0) {
visited[i][j] = -2
break
}
}
}
}
}
}
for(let i = 0; i < rows; i++) {
for(let j = 0; j < cols; j++) {
if(visited[i][j] === -2) grid[i][j] = color
}
}
return grid
};
function dfs(row, col, target, rows, cols, visited, grid, dirs) {
if(row >= rows || col >= cols || row < 0 || col < 0 || grid[row][col] !== target || visited[row][col] === -1) {
return
}
visited[row][col] = -1
for(let dir of dirs) {
dfs(row + dir[0], col+dir[1], target, rows, cols, visited, grid, dirs)
}
}