[백준 2210] 숫자판 점프 with node.js

waterglasses·2021년 11월 11일
0

📌 문제

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

📌 풀이

  • 대부분 DFS로 풀지만 BFS로 풀어보았다.
  • 숫자를 하나하나 연결하면서 queue에 넣고 길이가 6이 되었을 때 Set에 넣는 방법으로 풀었습니다.

📌 코드

const fs = require('fs');
const stdin = (
  process.platform === 'linux'
    ? fs.readFileSync('/dev/stdin').toString().trim()
    : `1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 2 1
1 1 1 1 1`
).split('\n');

const input = (() => {
  let line = 0;
  return () => stdin[line++];
})();

const addMakedNums = (startX, startY) => {
  const queue = [[startX, startY, board[startX][startY]]];
  let dx = [0, 0, 1, -1];
  let dy = [1, -1, 0, 0];

  while (queue.length) {
    const [x, y, num] = queue.shift();

    for (let i = 0; i < 4; i++) {
      let nx = x + dx[i];
      let ny = y + dy[i];

      if (nx < 0 || nx >= 5 || ny < 0 || ny >= 5) continue;

      let connectedNum = num + board[nx][ny];
      if (connectedNum.length === 6) {
        numsOfMaked.add(connectedNum);
      } else {
        queue.push([nx, ny, connectedNum]);
      }
    }
  }
};

const board = Array.from(Array(5), () => input().split(' '));
let numsOfMaked = new Set([]);

for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 5; j++) {
    addMakedNums(i, j);
  }
}
console.log(numsOfMaked.size);
profile
매 순간 성장하는 개발자가 되려고 노력하고 있습니다.

0개의 댓글