λ¬Έμ
νμ΄ κ³Όμ
X
λ‘ λλ¬μΈμΈ O
λΆλΆμ λͺ¨λ λ€μ§μμ λ μ΅μ’
μ μΌλ‘ μ΄λ€ ννλ₯Ό κ°μ§ board
κ° λλμ§ κ΅¬νλ λ¬Έμ μ
λλ€.
μ΄λ νκ°μ§ μ£Όμν μ μ λλ¬μΈλ ν
λλ¦¬κ° board
μ κ²½κ³ μμ μ‘΄μ¬νλ©΄ μλλ€λ μ μ
λλ€. BFS
λ₯Ό μ¬μ©νμ¬ λ¬Έμ λ₯Ό ν΄κ²°νμμΌλ©° νμ¬ μ’νμμ μνμ’μ°λ‘ μ΄λνμ λboard
λ₯Ό λ²μ΄λμ§ μλμ§ μ²΄ν¬ν΄μ 쑰건μ κ²μ¬ν΄μ€¬μ΅λλ€.
λ¬Έμ λ₯Ό νλ©΄μ λ°μνλ μ΄μ μ€ νλλ ES6
μ Map
μλ£κ΅¬μ‘°μ κ΄λ ¨λ λ΄μ©μ
λλ€.
μ²μμλ λ°©λ¬Έ μ’νλ₯Ό λ°°μ΄ ν€κ°μΌλ‘ Map
μ μ μ₯νλ €κ³ νλλ° ν
μ€νΈν΄λ³΄λκΉ
ν€ κ°μΌλ‘ λ°°μ΄μ μ¬μ©ν κ²½μ° μ¬λ°λ₯΄κ² λμνμ§ μμμ΅λλ€.
(λ§μ½ μ΄λ κ² νκ³ μΆμΌλ©΄ λ°°μ΄μ λ€λ₯Έ λ³μμ ν λΉν λ€ ν λΉλ λ³μκ°μ νμ©ν΄ ν€λ‘ μ§μ νκ³ has, get
λ±μ μ°μ°μ ν΄μΌν©λλ€.)
λ°λΌμ κ·Έλ₯ 2μ°¨μ λ°°μ΄μ μμ±ν΄μ visit
μ¬λΆλ₯Ό νλ¨ν΄μ€¬μ΅λλ€.
μ½λ
/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solve = function (board) {
if (!board.length) return board;
const N = board.length,
M = board[0].length;
const visit = new Array(N).fill(null).map((row) => new Array(M).fill(0));
function bfs(x, y) {
let surrounded = true;
const Q = [];
const pos = [];
const moves = [
[0, 1],
[0, -1],
[1, 0],
[-1, 0],
];
visit[x][y] = 1;
pos.push([x, y]);
Q.push([x, y]);
while (Q.length) {
const [x, y] = Q.shift();
for (let [dx, dy] of moves) {
const nx = dx + x,
ny = dy + y;
if (nx < 0 || nx >= N || ny < 0 || ny >= M) surrounded = false;
else {
if (!visit[nx][ny] && board[nx][ny] === "O") {
pos.push([nx, ny]);
Q.push([nx, ny]);
visit[nx][ny] = 1;
}
}
}
}
return [pos, surrounded];
}
for (let x = 0; x < board.length; x++) {
for (let y = 0; y < board[0].length; y++) {
if (board[x][y] === "O" && !visit[x][y]) {
const [pos, surrounded] = bfs(x, y);
if (surrounded) {
pos.forEach((p) => (board[p[0]][p[1]] = "X"));
}
}
}
}
return board;
};
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 617 - Merge Two Binary Trees (Easy) (0) | 2021.03.03 |
---|---|
LeetCode 98 - Validate Binary Search Tree (Medium) (0) | 2021.03.03 |
LeetCode 226 - Invert Binary Tree (Easy) (0) | 2021.03.03 |
LeetCode 406 - Queue Reconstruction by Height (Medium) (0) | 2021.03.03 |
LeetCode 54 - Spiral Matrix (Medium) (0) | 2021.03.03 |
π¬ λκΈ