// 섬의 개수
const filePath = process.platform === "linux" ? "/dev/stdin" : "input.txt";
const input = require('fs').readFileSync(filePath).toString().trim().split(/\n/);
const sol = (input) =>{
let arr = input;
// 123
// 456 , 5는 제외 가운데니깐!
// 789
const dx = [-1,0,1,-1,1,-1,0,1];
const dy = [1,1,1,0,0,-1,-1,-1];
const result = [];
while(arr.length){
const [w,h] = arr[0].split(' ').map(Number);
if(w===0 && h===0) break;
arr = arr.slice(1);
const graph = Array.from(Array(h),() => new Array());
for(let i=0; i<h; i++){
graph[i] = arr[i].split(' ').map(Number);
}
// for(let i=0;i<h; i++){
// console.log(graph[i]);
// }
const dfs =(x,y) =>{
if(x<0 || x>=w || y<0 || y>=h) return false;
if(graph[y][x] === 1){
graph[y][x] = 0;
// console.log(`y: ${y}`);
// console.log(`g: ${graph[y]}`)
for(let i=0; i<8; i++){
dfs(x+dx[i], y+dy[i]);
}
return true;
}
return false;
}
let count = 0;
for(let i=0; i<h;i++){
for(let j=0; j<w; j++){
dfs(j,i) ? count++ : null;
// !(i===0 && j===0) ? result.push() : null;
}
}
result.push(count);
arr= arr.slice(h);
}
console.log(result.join('\n'));
}
sol(input);
입력값을 가공하는데 잘못 가공해서 한참을 헤맸다.. 아무리봐도 로직에 문제는 없는데 혹시했는데..
문제 자체는 단지번호붙이기를 풀었다면 금방 풀수있따~
'알고리즘 > 백준' 카테고리의 다른 글
[boj 7576] 토마토 -js (0) | 2022.03.14 |
---|---|
[boj 2178] 미로탐색 -js (0) | 2022.03.14 |
[boj 2667] 단지번호붙이기 -js (0) | 2022.03.13 |
[boj 11724] 이분 그래프 -js (0) | 2022.03.13 |
[boj 11724] 연결 요소의 개수 -js (0) | 2022.03.13 |