-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0130-surrounded-regions.js
55 lines (47 loc) · 1.23 KB
/
0130-surrounded-regions.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
50
51
52
53
54
55
/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solve = function (board) {
let rows = board.length
let cols = board[0].length
var dfs = function (start, end) {
if (start < 0 || start >= rows || end < 0 || end >= cols || board[start][end] != "O") {
return
}
board[start][end] = "B"
for (let [r, c] of [[-1, 0], [1, 0], [0, -1], [0, 1]]) {
let x = r + start
let y = c + end
dfs(x, y)
}
}
// check all rows
for (let i = 0; i < rows; i++) {
if (board[i][0] == "O") {
dfs(i, 0)
}
if (board[i][cols - 1] == "O") {
dfs(i, cols - 1)
}
}
for (let i = 0; i < cols; i++) {
if (board[0][i] == "O") {
dfs(0, i)
}
if (board[rows - 1][i] == "O") {
dfs(rows - 1, i)
}
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (board[i][j] == "O") {
board[i][j] = "X"
}
else if (board[i][j] == 'B') {
board[i][j] = "O"
}
}
}
return board
};