본문 바로가기
Algorithm/삼성 SW 역량 테스트 기출 문제

[Baekjoon][3190] 뱀

by 어발 2022. 1. 17.

출처 - 백준사이트

3190번: 뱀

나의 풀이

#include <cstring>
#include <iostream>
#include <deque>

#define MAX 100

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

using namespace std;

int N, K, L, result;
int map[MAX][MAX];    // -1:  맵이 아닌곳, 0: 맵, 1: 뱀, 2: 사과
deque<pair<int, char>> move_stack;
deque<pair<int,int>> snake;

void print_map() {
    cout << "\n";

    for (int y = 0; y < N ; y++) {
        for (int x = 0 ; x < N ; x++)
            cout << map[y][x];

        cout << "\n";
    }
}

int main() {
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);

    cin >> N;
    cin >> K;

    for (int y = 0 ; y < N ; y++) {
        for (int x = 0 ; x < N ; x++)
            map[y][x] = 0;
    }

    for (int idx = 0 ; idx < K ; idx++) {
        int x, y;

        cin >> y >> x;
        map[y - 1][x - 1] = 2;
    }

    cin >> L;

    for (int idx = 0 ; idx < L ; idx++) {
        int X;
        char C;

        cin >> X >> C;
        move_stack.push_back({X, C});
    }

    map[0][0] = 1;
    snake.push_back({0,0});

    bool isBreak = false;
    int dir = 1, nx = 0, ny = 0;
    while (!isBreak) {
        ny += dy[dir], nx += dx[dir];

        if ((0 > ny) || (ny >= N) || (0 > nx) || (nx >= N)) // 벽 만남
            isBreak = true;
        else if (map[ny][nx] == 1) // 몸을 만났으면
            isBreak = true;
        else if (map[ny][nx] == 0) { // 사과없는 맵을 만났을때
            map[ny][nx] = 1;
            snake.push_front({snake[0].first + dy[dir], snake[0].second + dx[dir]});
            pair<int, int> del = snake.back();
            map[del.first][del.second] = 0;
            snake.pop_back();
        }
        else if (map[ny][nx] == 2) { // 사과먹었을 때
            map[ny][nx] = 1;
            snake.push_front({snake[0].first + dy[dir], snake[0].second + dx[dir]});
        }

        result++;

        if (!move_stack.empty() && (move_stack[0].first == result)) { // 방향바꾸기
            switch (move_stack[0].second) {
            case 'L':
                dir += -1;

                break;
            case 'D':
                dir += 1;

                break;
            default:
                break;
            }

            dir += 4;
            dir %= 4;
            move_stack.pop_front();
        }
    }

    cout << result;

    return 0;
}
728x90

댓글