๐ŸŽฒ ๋ฐฑ์ค€ 2667๋ฒˆ ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ

Jeongeunยท2023๋…„ 5์›” 21์ผ

๋ฐฑ์ค€

๋ชฉ๋ก ๋ณด๊ธฐ
63/188

๋ฐฑ์ค€ 2667๋ฒˆ

๐Ÿ’Š 1์ธ ๊ณณ์„ ์–ด๋–ป๊ฒŒ ์ฐพ์•„์•ผํ•˜์ง€ ํ•˜๊ณ  ๊ทธ๋ƒฅ BFS๋กœ ๋‹ค ์ฒดํฌํ–ˆ๋Š”๋ฐ ์ด์ค‘ for์„ ๋Œ๋ ค 1์„ ์ฐพ๊ณ  BFS๋กœ 1์ธ ๊ณณ๋งŒ ์ฒดํฌํ•˜๋ฉด ๋˜๋Š” ๊ฒƒ์ด์—ˆ๋‹ค.

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

const N = +input.shift();

const arr = input.map((item) => item.split("").map((item) => Number(item)));

const dir = [
  [0, 1],
  [0, -1],
  [1, 0],
  [-1, 0],
];
const checked = [];
for (let i = 0; i < N; i++) {
  checked.push(new Array(N).fill(0));
}
const willChecked = [];
let count = 0;
let block = [];

const BFS = (i, j) => {
  willChecked.push([i, j]);
  while (willChecked.length) {
    const [y, x] = willChecked.shift();
    if(checked[y][x]===0){
      checked[y][x] = 1;
      count++;
  
      for (let i = 0; i < 4; i++) {
        nextX = x + dir[i][1];
        nextY = y + dir[i][0];
  
        if (
          nextX >= 0 &&
          nextY >= 0 &&
          nextX < N &&
          nextY < N
        ) {
          if (arr[nextY][nextX] === 1) {
            willChecked.push([nextY, nextX]);
          }
        }
      }
    }
    
  }
};

for (let i = 0; i < N; i++) {
  for (let j = 0; j < N; j++) {
    if (arr[i][j] === 1 && checked[i][j] === 0) {
      BFS(i, j);
      block.push(count);
      count = 0;
    }
  }
}
console.log(block.length);
block.sort((a, b) => a - b);
block.map((item) => console.log(item));

0๊ฐœ์˜ ๋Œ“๊ธ€