티스토리 뷰

알고리즘/백준

백준1012[nodejs]유기농 배추

민트초코수장 2021. 2. 4. 00:42
const readline = require("readline");

let input = [];
let cabbageField = [];
let result = [];
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on("line", (line) => input.push(line.trim())).on("close", () => {
  const test = parseInt(input[0]);
  input.splice(0, 1);
  //여러 밭이 나올 수 있어 for문으로 반복
  for (let repeat = 0; repeat < test; repeat++) {
    let count = 0;
    const [x, y, size] = input[0].split(" ").map(Number);
    input.splice(0, 1);

    cabbageField = Array.from(Array(y), () => Array(x).fill(0));

    for (let i = 0; i < size; i++) {
      let cabbage = input[i].split(" ").map(Number);
      cabbageField[cabbage[1]][cabbage[0]] = 1;
    }
    //배추밭 만들기
    for (let i = 0; i < cabbageField.length; i++) {
      for (let j = 0; j < cabbageField[i].length; j++) {
        if (dfs(i, j, y, x)) count++;
      }
    }

    result.push(count);
    input.splice(0, size);
    cabbageField.length = 0;
  }
  console.log(result.join("\n"));
});

const dfs = (x, y, xLength, yLength) => {
  if (x < 0 || x > xLength - 1 || y < 0 || y > yLength - 1) return false;
  if (cabbageField[x][y] === 1) {
    cabbageField[x][y] = 2;
    dfs(x + 1, y, xLength, yLength);
    dfs(x - 1, y, xLength, yLength);
    dfs(x, y + 1, xLength, yLength);
    dfs(x, y - 1, xLength, yLength);
    return true;
  }
  return false;
};

 

 아까 단지번호붙이기와 비슷한 dfs를 이용한 코드이다.

여기서 다른점은 x와 y가 다르기때문에 둘의 길이도 맞춰줘야한다는 점이다.

 

반응형

'알고리즘 > 백준' 카테고리의 다른 글

백준 7576 [nodejs] 토마토  (0) 2021.02.04
백준2178[nodejs] 미로 탐색  (0) 2021.02.04
백준2667[nodejs]단지번호붙이기  (0) 2021.02.04
백준2606[nodejs] 바이러스  (0) 2021.02.04
백준1260[nodejs] DFS와 BFS  (0) 2021.02.03
Comments