[백준알고리즘] 알고리즘 연습 - 4963

krkorklo·2022년 3월 5일
0

백준알고리즘

목록 보기
27/27

4963 - 섬의 개수

https://www.acmicpc.net/problem/4963

let fs = require('fs');
let input = fs.readFileSync('/dev/stdin').toString().split('\n');

for(let i=0; i<input.length;) {
    let [w, h] = input[i++].split(" ").map((n) => Number(n));
    if (w == 0 && h == 0) break;
    let numbers = [];
    for(let j=0; j<h; j++, i++) {
        numbers.push(input[i].split(" ").map((n) => Number(n)));
    }
    console.log(answer(w, h, numbers));
}

function answer(w, h, input){
    let visited = Array.from(Array(h), () => Array(w).fill(false));
    let ans = 0;
    for(let i=0; i<h; i++) {
        for(let j=0; j<w; j++) {
            if(visited[i][j] || input[i][j] == 0) continue;
            let queue = [[i, j]];
            let idx = 0;
            while(queue.length != idx) {
                let [x, y] = queue[idx++];
                if(visited[x][y]) continue;
                visited[x][y] = true;
                if (x != 0 && input[x-1][y] == 1) queue.push([x-1, y]);
                if (y != 0 && input[x][y-1] == 1) queue.push([x, y-1]);
                if (x != h-1 && input[x+1][y] == 1) queue.push([x+1, y]);
                if (y != w-1 && input[x][y+1] == 1) queue.push([x, y+1]);
                if (x != 0 && y != 0 && input[x-1][y-1] == 1) queue.push([x-1, y-1]);
                if (x != 0 && y != w-1 && input[x-1][y+1] == 1) queue.push([x-1, y+1]);
                if (x != h-1 && y != 0 && input[x+1][y-1] == 1) queue.push([x+1, y-1]);
                if (x != h-1 && y != w-1 && input[x+1][y+1] == 1) queue.push([x+1, y+1]);
            }
            ans++;
        }
    }
    return ans;
}

0개의 댓글