티스토리 뷰

알고리즘/백준(BOJ)

백준 - 3190 뱀

시나모온 2020. 10. 15. 01:31

문제 링크입니다 : www.acmicpc.net/problem/3190

 

3190번: 뱀

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

www.acmicpc.net

역시 구현 문제 난이도는 중상정도

 

 

 

 

 

 

 

#include <iostream>
#include <vector>
#define SNAKE 1
#define APPLE 9

using namespace std;

const int dy[4] = {0, 1, 0, -1};
const int dx[4] = {1, 0, -1, 0};

int N;
vector<vector<int>> board;

struct State {
    int hy;
    int hx;
    int ty;
    int tx;
    int dir;

    State(int a, int b, int c, int d, int e) : hy(a), hx(b), ty(c), tx(d), dir(e) {

    }
};

int main() {
    cin >> N;
    board.assign(N, vector<int>(N, -1));

    int K, y, x, L;
    cin >> K;
    for(int i = 0; i < K; i++) {
        cin >> y >> x;
        board[y - 1][x - 1] = APPLE;
    }
    cin >> L;
    vector<pair<int, char>> cmd(L);

    for(int i = 0; i < L; i++) {
        cin >> cmd[i].first >> cmd[i].second;
    }


    State cur(0, 0, 0, 0, 0);
    board[0][0] = 0;
    
    int step = 1;
    int cmdIdx = 0;

    while(true) {
        int ny = cur.hy + dy[cur.dir];
        int nx = cur.hx + dx[cur.dir];
        if(ny < 0 || ny >= N || nx < 0 || nx >= N) break;
        if(board[ny][nx] >= 0 && board[ny][nx] < 4) break;

        // 헤드
        cur.hy = ny;
        cur.hx = nx;
        


        // 테일
        if(board[ny][nx] != APPLE) {
            int tny = cur.ty + dy[board[cur.ty][cur.tx]];
            int tnx = cur.tx + dx[board[cur.ty][cur.tx]];
            board[cur.ty][cur.tx] = -1;
            cur.ty = tny;
            cur.tx = tnx;
        }


        if(cmdIdx != cmd.size()) {
            if(cmd[cmdIdx].first == step) {
                if(cmd[cmdIdx].second == 'D') {
                    cur.dir = (cur.dir + 1) % 4;
                } else {
                    cur.dir = (cur.dir - 1 + 4) % 4;
                }
                cmdIdx++;
            }
        }
        
        board[ny][nx] = cur.dir;
        

        step++;
    }


    cout << step;

    return 0;
}

 

 

 

개발 환경 : vscode

지적, 조언, 질문 환영입니다! 댓글 남겨주세요~

 

'알고리즘 > 백준(BOJ)' 카테고리의 다른 글

백준 - 14499 주사위 굴리기  (0) 2020.10.15
백준 - 13458 시험 감독  (0) 2020.10.15
백준 - 13460 구슬 탈출 2  (0) 2020.10.14
백준 - 12100 2048(Easy)  (0) 2020.10.14
백준 - 14502 연구소  (0) 2020.10.05
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/06   »
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
글 보관함