728x90
문제
https://www.acmicpc.net/problem/3190
문제 해석
이 문제도 전체 배열에 뱀이 지나가는 부분과 뱀 길이, 그리고 각각의 방향을 신경 쓰면 풀 수 있는 문제이다.
문제의 조건에 따라 N, K, L 정수를 구한다음 전체 배열을 생성하고 사과가 있는 위치의 값을 1로 바꿔준다.
그 후 무한 반복문을 통해 각각의 조건에 맞춰서 이동하면 된다.
풀이
const filePath = process.platform === "linux" ? "dev/stdin" : "../test.txt";
const input = require("fs").readFileSync(filePath).toString().trim().split("\n");
function solution(input) {
const N = Number(input[0]);
const K = Number(input[1]);
const L = Number(input[2 + K]);
const dx = [0, 1, 0, -1];
const dy = [1, 0, -1, 0];
const bodyQueue = [];
let totalTime = 1;
let dir = 0;
const board = Array.from({ length: N + 1 }, () => new Array(N + 1).fill(0));
const directionArr = [];
for (let i = 2; i < 2 + K; i++) {
const [X, Y] = input[i].split(" ").map(Number);
board[X][Y] = 1;
}
for (let i = 0; i < L; i++) {
const [n, d] = input[K + 3 + i].split(" ");
directionArr.push([Number(n), d]);
}
const rotatePosition = directionArr.map((v) => v[0]);
let [x, y] = [1, 1];
board[x][y] = 2;
bodyQueue.push([x, y]);
while (true) {
const nx = x + dx[dir];
const ny = y + dy[dir];
if (nx <= 0 || nx >= N + 1 || ny <= 0 || ny >= N + 1) break;
if (board[nx][ny] === 2) break;
if (board[nx][ny] === 0) {
board[nx][ny] = 2;
const [tx, ty] = bodyQueue.shift();
board[tx][ty] = 0;
} else if (board[nx][ny] === 1) {
board[nx][ny] = 2;
}
const p = rotatePosition.indexOf(totalTime);
if (p !== -1) {
const d = directionArr[p][1];
if (d === "D") dir = (dir + 1) % 4;
else dir = (4 + dir - 1) % 4;
}
bodyQueue.push([nx, ny]);
x = nx;
y = ny;
totalTime++;
}
return totalTime;
}
console.log(solution(input));
끝
728x90
'WEB > 백준 문제 풀이' 카테고리의 다른 글
백준 17413번 단어 뒤집기 2 (node.js) (0) | 2024.05.24 |
---|---|
백준 14502번 연구소 (node.js) (0) | 2024.05.23 |
백준 11536번 줄 세우기 (node.js) (0) | 2024.05.21 |
백준 14504번 로봇 청소기 (node.js) (0) | 2024.05.20 |
백준 2578번 덩치 (node.js) (0) | 2024.05.18 |