연습장/백준(BOJ) 문제풀이

[백준 16173 - Node.js] 점프왕 쩰리 (Small)

Tesseractjh 2023. 1. 1. 20:20

🔗 문제 링크

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

 

16173번: 점프왕 쩰리 (Small)

쩰리는 맨 왼쪽 위의 칸에서 출발해 (행, 열)로 나타낸 좌표계로,  (1, 1) -> (2, 1) -> (3, 1) -> (3, 3)으로 이동해 게임에서 승리할 수 있다.

www.acmicpc.net

✏️ 풀이

const [[N], ...board] = require('fs')
  .readFileSync('/dev/stdin')
  .toString()
  .trim()
  .split('\n')
  .map(v => v.split(' ').map(Number));

const dfs = (x = 0, y = 0) => {
  const dist = board[x][y];

  // 도착한 경우
  if (dist === -1) {
    return true;
  }

  // 0이 적힌 칸
  if (!dist) {
    return false;
  }

  // 오른쪽으로 이동
  if (x + dist < N) {
    const result = dfs(x + dist, y);
    if (result) {
      return true;
    }
  }

  // 아래쪽으로 이동
  if (y + dist < N) {
    const result = dfs(x, y + dist);
    if (result) {
      return true;
    }
  }

  return false;
};

console.log(dfs() ? 'HaruHaru' : 'Hing');

DFS로 모든 경우를 탐색 시도하였다. 만약 도착점으로 가는 경우를 발견하면 즉시 탐색을 멈추도록 하였다.