문제
제한 사항
입출력 예
풀이
function solution(board) {
let answer = 0;
let n = board.length;
let dx = [-1, -1, 0, 1, 1, 1, 0, -1];
let dy = [0, 1, 1, 1, 0, -1, -1, -1];
function DFS(x, y) {
board[x][y] = 0;
for (let k = 0; k < dx.length; k++) {
let nx = x + dx[k];
let ny = y + dy[k];
if (nx >= 0 && ny >= 0 && nx < n && ny < n && board[nx][ny]) {
DFS(nx, ny);
}
}
}
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (board[i][j] === 1) {
DFS(i, j);
answer++;
}
}
}
return answer;
}
let arr = [
[1, 1, 0, 0, 0, 1, 0],
[0, 1, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 1],
[1, 1, 0, 1, 1, 0, 0],
[1, 0, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0],
];
console.log(solution(arr));
function solution2(board) {
let answer = 0;
let n = board.length;
function bfs(i, j) {
let dx = [-1, -1, 0, 1, 1, 1, 0, -1];
let dy = [0, 1, 1, 1, 0, -1, -1, -1];
let queue = [];
queue.push([i, j]);
while (queue.length) {
let [x, y] = queue.shift();
for (let i = 0; i < dx.length; i++) {
let nx = x + dx[i];
let ny = y + dy[i];
if (nx >= 0 && ny >= 0 && nx < n && ny < n && board[nx][ny]) {
board[nx][ny] = 0;
queue.push([nx, ny]);
}
}
}
}
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (board[i][j] === 1) {
board[i][j] = 0;
answer++;
bfs(i, j);
}
}
}
return answer;
}
let arr2 = [
[1, 1, 0, 0, 0, 1, 0],
[0, 1, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 1],
[1, 1, 0, 1, 1, 0, 0],
[1, 0, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0],
];
console.log(solution2(arr2));