21610. 마법사 상어와 비바라기 - node.js / javascript

윤상준·2022년 6월 30일
0

BOJ - node.js / javascript

목록 보기
51/55
post-thumbnail

문제

내 코드

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

function solution(input) {
  let [N, M] = input[0].split(" ").map(Number);
  let board = input.slice(1, N + 1).map((v) => v.split(" ").map(Number));
  let moves = input.slice(N + 1).map((v) => v.split(" ").map(Number));
  let clouds = [
    [N - 2, 0],
    [N - 2, 1],
    [N - 1, 0],
    [N - 1, 1],
  ];
  const directions = {
    1: [0, -1],
    2: [-1, -1],
    3: [-1, 0],
    4: [-1, 1],
    5: [0, 1],
    6: [1, 1],
    7: [1, 0],
    8: [1, -1],
  };
  const diagX = [-1, -1, 1, 1];
  const diagY = [-1, 1, -1, 1];
  let answer = 0;

  for (let move of moves) {
    // 1번
    const nextClouds = [];
    for (let cloud of clouds) {
      const [row, col] = cloud;
      const direction = directions[move[0]];
      const distance = move[1];
      let nRow = (row + direction[0] * distance) % N;
      let nCol = (col + direction[1] * distance) % N;
      nRow = nRow < 0 ? nRow + N : nRow;
      nCol = nCol < 0 ? nCol + N : nCol;
      nextClouds.push([nRow, nCol]);
    }

    // 2번
    let visited = Array.from({ length: N }, () => Array(N).fill(false));
    for (let cloud of nextClouds) {
      const [row, col] = cloud;
      board[row][col]++;
      visited[row][col] = true;
    }

    // 3번
    clouds = [];

    // 4번
    for (let cloud of nextClouds) {
      const [row, col] = cloud;
      let count = 0;
      for (let i = 0; i < 4; i++) {
        const [nRow, nCol] = [row + diagX[i], col + diagY[i]];
        if (nRow < 0 || nRow >= N || nCol < 0 || nCol >= N || board[nRow][nCol] < 1) continue;
        count++;
      }
      board[row][col] += count;
    }

    // 5번
    for (let row = 0; row < N; row++) {
      for (let col = 0; col < N; col++) {
        if (board[row][col] >= 2 && !visited[row][col]) {
          board[row][col] -= 2;
          clouds.push([row, col]);
        }
      }
    }
  }

  // 최종 계산
  for (let row = 0; row < N; row++) {
    for (let col = 0; col < N; col++) {
      answer += board[row][col];
    }
  }
  return answer;
}

console.log(solution(input));

깃허브 링크

https://github.com/highjoon/Algorithm/blob/master/BOJ/21610.js

후기

파이썬으로 푼 사람들은 음수에 바로 나머지 연산을 하던데 (모듈러)
이런거 보면 파이썬이 더 좋아보이긴 한다.
아직 부족해서 문제를 풀다보면 풀이를 검색해보기 마련인데 죄다 파이썬 아니면 C, C++ 풀이만 나오는 것도 사실 애로사항이다.
근데 문법이 익숙하지 않고 백준 입출력 받는 방식이 많이 달라서 언어를 바꿀 엄두가 나지 않는다.
자바스크립트가 너무 익숙해져버렸다.

profile
하고싶은건 많은데 시간이 없다!

0개의 댓글

관련 채용 정보