티스토리 뷰

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

 

4963번: 섬의 개수

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도

www.acmicpc.net

const fs = require('fs');
const input = fs.readFileSync("./dev/stdin").toString().trim().split("\n").map(v=>v.split(' ').map(x=>+x));

const dir = [
  [-1,0],
  [-1,1],
  [0,1],
  [1,1],
  [1,0],
  [1,-1],
  [0,-1],
  [-1,-1]
]

let answer = []
for(let i = 0; i< input.length-1; i++){
  const [C,R] = input[i];
  const map = [];
  for(let j = 1; j<=R; j++){
    map.push(input[j+i])
  }
  i+=R;

  let island = 0;
  for(let r = 0; r<R; r++){
    for(let c = 0; c<C; c++){
      if(map[r][c]==1){
        island++;
        let q = [[r,c]];
        while(q.length>0){
          const [islandR,islandC]= q.shift();
          dir.forEach(v=>{
            const x = v[0];
            const y = v[1];
            if(x+islandR>=0 && x+islandR<R && y+islandC>=0 && y+islandC<C && map[x+islandR][y+islandC]==1){
              map[x+islandR][y+islandC]=0;
              q.push([x+islandR,y+islandC])
            }
          })
        }
      }
    }
  }
  answer.push(island)
}
console.log(answer.join('\n'))
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함