반응형
문제
N*N의 섬나라 아일랜드의 지도가 격자판의 정보로 주어집니다. 각 섬은 1로 표시되어 상하좌
우와 대각선으로 연결되어 있으며, 0은 바다입니다. 섬나라 아일랜드에 몇 개의 섬이 있는지
구하는 프로그램을 작성하세요.
풀이
#1 DFS
function solution(arr) {
const n = arr.length;
const dx = [-1, -1, 0, 1, 1, 1, 0, -1];
const dy = [0, 1, 1, 1, 0, -1, -1, -1];
let answer = 0;
function DFS(x, y) {
for (let i = 0; i < 8; i++) {
const nx = x + dx[i];
const ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < n && arr[nx][ny] === 1) {
arr[nx][ny] = 0;
DFS(nx, ny);
}
}
}
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (arr[i][j] === 1) {
arr[i][j] = 0;
DFS(i, j);
answer += 1;
}
}
}
return answer;
}
#1 BFS
function solution(arr) {
const n = arr.length;
const dx = [-1, -1, 0, 1, 1, 1, 0, -1];
const dy = [0, 1, 1, 1, 0, -1, -1, -1];
let q = [];
let answer = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (arr[i][j] === 1) {
q.push([i, j]);
arr[i][j] = 0;
while (q.length) {
const [x, y] = q.shift();
for (let k = 0; k < 8; k++) {
const nx = x + dx[k];
const ny = y + dy[k];
if (nx >= 0 && nx < n && ny >= 0 && ny < n && arr[nx][ny] === 1) {
q.push([nx, ny]);
arr[nx][ny] = 0;
}
}
}
answer += 1;
}
}
}
return answer;
}
반응형
'Algorithm > Inflearn' 카테고리의 다른 글
[알고리즘/인프런] 뒤집은 소수 (0) | 2023.05.29 |
---|---|
[알고리즘/인프런] 멘토링 (0) | 2023.05.29 |
[알고리즘/인프런] 송아지 찾기 (0) | 2023.05.21 |
[알고리즘/인프런] 미로탐색 (0) | 2023.05.21 |
[알고리즘/인프런] 경로탐색(인접 리스트) (0) | 2023.05.21 |