[JS] BOJ_1012 - 유기농 배추

GIGI·2023년 2월 23일

BOJ in Java

목록 보기
6/18
post-thumbnail


const fs = require("fs");
const filePath =
  process.platform === "linux" ? "/dev/stdin" : __dirname + "/input.txt";
let input = fs.readFileSync(filePath).toString().split("\n");
let dir = [
  [-1, 0],
  [1, 0],
  [0, 1],
  [0, -1],
];
let graph, m, n, k; // test case에 따라 달라지는 값 선언
const T = +input.shift();

// 지렁이 삽입
const putWorms = () => {
  let res = 0;
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if (graph[i][j] == 1) {
        bfs(i, j);
        res++;
      }
    }
  }
  console.log(res);
};

const bfs = (sx, sy) => {
  const queue = [[sx, sy]];
  while (queue.length) {
    const [x, y] = queue.shift();
    if (!graph[x][y]) continue;
    else graph[x][y] = 0;
    for (let i = 0; i < 4; i++) {
      const px = x + dir[i][0];
      const py = y + dir[i][1];
      if (px < 0 || py < 0 || (px >= n) | (py >= m)) continue;
      if (graph[px][py]) queue.push([px, py]);
    }
  }
};

for (let tc = 0; tc < T; tc++) {
  [m, n, k] = input.shift().split(" ").map(Number);
  graph = [...Array(n)].map((e) => Array(m).fill(0));
  for (let i = 0; i < k; i++) {
    let [x, y] = input[i].split(" ").map(Number);
    graph[y][x] = 1;
  }
  putWorms();
  input.slice(k);
  input = input.slice(k);
}
  1. test case에 따라 달라지는 값들은 let으로 상단에 선언해준다.
  2. 배열 생성 [...Array(세로)].map((e)=> Array(세로).fill(0));
  3. input = input.slice(숫자)를 해주어야 원본이 잘라진다.
profile
이제 누구도 날 막을 수 없다!!!!!!!!!!

0개의 댓글