Skip to content

Commit dcc1a73

Browse files
committed
[leet] surrounded region (mid)
1 parent 2c230bd commit dcc1a73

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

허현빈/7주차/260209.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
var solve = function (board) {
2+
if (!board.length) return;
3+
4+
const rows = board.length;
5+
const cols = board[0].length;
6+
const visited = Array.from({ length: rows }, () => Array(cols).fill(false));
7+
const dir = [
8+
[1, 0],
9+
[-1, 0],
10+
[0, 1],
11+
[0, -1],
12+
];
13+
14+
const bfs = (r, c) => {
15+
const queue = [[r, c]];
16+
const path = [[r, c]];
17+
visited[r][c] = true;
18+
let isSurrounded = true;
19+
20+
while (queue.length) {
21+
const [curY, curX] = queue.shift();
22+
23+
if (curY === 0 || curY === rows - 1 || curX === 0 || curX === cols - 1) {
24+
isSurrounded = false;
25+
}
26+
27+
for (let i = 0; i < dir.length; i++) {
28+
const ny = curY + dir[i][0];
29+
const nx = curX + dir[i][1];
30+
31+
if (
32+
ny >= 0 &&
33+
ny < rows &&
34+
nx >= 0 &&
35+
nx < cols &&
36+
board[ny][nx] === "O" &&
37+
!visited[ny][nx]
38+
) {
39+
visited[ny][nx] = true;
40+
queue.push([ny, nx]);
41+
path.push([ny, nx]);
42+
}
43+
}
44+
}
45+
46+
if (isSurrounded) {
47+
for (const [y, x] of path) {
48+
board[y][x] = "X";
49+
}
50+
}
51+
};
52+
53+
for (let i = 0; i < rows; i++) {
54+
for (let j = 0; j < cols; j++) {
55+
if (board[i][j] === "O" && !visited[i][j]) {
56+
bfs(i, j);
57+
}
58+
}
59+
}
60+
};

0 commit comments

Comments
 (0)