티스토리 뷰

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

 

3190번: 뱀

 'Dummy' 라는 도스게임이 있다. 이 게임에는 뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다. 게임

www.acmicpc.net

구현

 

사과를 먹으면 뱀이 늘어난다.  

const fs = require('fs');
const input = fs.readFileSync("./dev/stdin").toString().trim().split("\n").map(v => v.trim())
const N = +input.shift();
let board = Array.from(Array(N), () => Array(N).fill(0));
const breakPoint = [];
const snake = [[0, 0]];
board[0][0] = 'X'
const A = +input.shift();
for (let i = 0; i < A; i++) {
  const [x, y] = input.shift().split(' ').map(Number)
  board[x - 1][y - 1] = 'A'
}

const d = +input.shift();

for (let i = 0; i < d; i++) {
  breakPoint.push(input.shift().split(' ').map((v, i) => { if (i == 0) return +v; else return v }));
}

const dirSet = {
  'R': [0, 1],
  'L': [0, -1],
  'D': [1, 0],
  'U': [-1, 0],
}

let dir = 'R'
let time = 0;
while (true) {
  time++;
  const [x, y] = snake[snake.length - 1]; //head
  const nx = x + dirSet[dir][0];
  const ny = y + dirSet[dir][1];
  if (nx >= 0 && ny >= 0 && nx < N && ny < N && board[nx][ny] != 'X') {
    snake.push([nx, ny]);
    if (board[nx][ny] != 'A') {
      const [px, py] = snake.shift();
      board[px][py] = 0;

    }
    board[nx][ny] = 'X';
  } else {
    break;
  }
  if (breakPoint.length > 0 && time == breakPoint[0][0]) {
    const [_, changeDir] = breakPoint.shift();
    switch (dir) {
      case 'R':
        if (changeDir == 'L') dir = 'U'
        else dir = 'D'
        break;
      case 'L':
        if (changeDir == 'L') dir = 'D'
        else dir = 'U'
        break;
      case 'U':
        if (changeDir == 'L') dir = 'L'
        else dir = 'R'
        break;
      case 'D':
        if (changeDir == 'L') dir = 'R'
        else dir = 'L'
        break;
    }
  }
}

console.log(time)
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함