3190 : 뱀

CS·2026년 2월 16일

SSPS

목록 보기
5/10

formula

사과를 먹어야 길이가 확장됨
덱에 머리와 꼬리를 끝에 위치시켜서
이동할때마다 머리 위치를 업데이트시켜주고(push_front)

사과를 먹었다면 꼬리 위치인 back은 유지하고
못먹었으면 pop_back으로 날려줌

이외에는 회전 공식 사용말고 없음

Implementation

#include <iostream>
#include <vector>
#include <deque>  
#include <queue>  

using namespace std;

int N, K, L;
int board[101][101]; // 0:빈칸, 1:사과, 2:뱀

// 상 우 하 좌 
int dx[] = { -1, 0, 1, 0 };
int dy[] = { 0, 1, 0, -1 };

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    // Init
    cin >> N >> K;

    for (int i = 0; i < K; i++) {
        int r, c;
        cin >> r >> c;
        board[r - 1][c - 1] = 1;
    }

    cin >> L;
    queue<pair<int, char>> cmd; 

    for (int i = 0; i < L; i++) {
        int t;
        char c;
        cin >> t >> c;
        cmd.push({ t, c });
    }

    deque<pair<int, int>> snake;
    snake.push_front({ 0, 0 }); // 시작 위치
    board[0][0] = 2;            
    int dir = 1;                // 우측 보며 시작
    int time = 0;               

    // Implementation
    while (true) {
        time++; 

        // dx,dx[dir]로 증분
        int nx = snake.front().first + dx[dir];
        int ny = snake.front().second + dy[dir];

        // 탈출조건
        if (nx < 0 || nx >= N || ny < 0 || ny >= N || board[nx][ny] == 2) {
            break;
        }

        // 머리 이동
        snake.push_front({ nx, ny });
        // 사과 있으면
        if (board[nx][ny] == 1) {
            // 뱀 길이 확장
            board[nx][ny] = 2;
        }
        else {
            // 사과 없으면 길이 유지
            board[nx][ny] = 2;

            int tail_x = snake.back().first;
            int tail_y = snake.back().second;
            board[tail_x][tail_y] = 0; 
            snake.pop_back();         
        }

        // 방향 체크
        if (!cmd.empty()) {
            if (time == cmd.front().first) {
                char c = cmd.front().second;
                if (c == 'L') dir = (dir + 3) % 4; // rotate 좌측
                else dir = (dir + 1) % 4;          // rotate 우측
                cmd.pop();
            }
        }
    }

    cout << time << endl;
    return 0;
}
profile
학습

0개의 댓글