Make Unreal REAL.
article thumbnail
Level 1. 공원 산책

 

 

시작점을 직접 찾아야 하고 좌표가 2차원 벡터가 아닌, 문자열 벡터로 주어져서 조금 까다로운 문제였다.

 

#include <iostream>
#include <vector>

using namespace std;

vector<int> solution(vector<string> park, vector<string> routes)
{
    vector<int> current(2);
    int H = park.size(), W = park.front().length();

    auto dir = [](string& s) -> vector<int>
    {
        switch (s[0])
        {
        case 'E': return vector<int> {0, 1};
        case 'W': return vector<int> {0, -1};
        case 'S': return vector<int> {1, 0};
        case 'N': return vector<int> {-1, 0};
        }
    };

    auto dist = [](string& s) { return s[2] - '0'; };

    auto check_obstacle = [](vector<int>& current, vector<string>& park, vector<int>& direction) -> bool
    {
        int start = (0 <= direction[0]) ? current[0] : current[0] + direction[0];
        int end   = (0 <= direction[0]) ? current[0] + direction[0] : current[0];

        for (int h = start; h <= end; ++h)
            if (park[h][current[1]] == 'X')
                return true;

        start = (0 <= direction[1]) ? current[1] : current[1] + direction[1];
        end   = (0 <= direction[1]) ? current[1] + direction[1] : current[1];

        for (int w = start; w <= end; ++w)
            if (park[current[0]][w] == 'X')
                return true;

        return false;
    };

    for (int h = 0; h < H; ++h)
    {
        for (int w = 0; w < W; ++w)
        {
            if (park[h][w] == 'S')
            {
                current[0] = h;
                current[1] = w;
                h = H;
                w = W;
            }
        }
    }

    for (string& route : routes)
    {
        vector<int> direction = dir(route);
        int distance = dist(route);
        
        direction[0] *= distance;
        direction[1] *= distance;

        if (current[0] + direction[0] < 0 || H <= current[0] + direction[0])
            continue;
        else if (current[1] + direction[1] < 0 || W <= current[1] + direction[1])
            continue;
        else if (check_obstacle(current, park, direction))
            continue;

        current[0] += direction[0];
        current[1] += direction[1];
    }

    return current;
}

'자료구조 & 알고리즘 > 프로그래머스' 카테고리의 다른 글

Level 2. 예상 대진표  (0) 2023.04.20
Level 1. 시저 암호  (0) 2023.04.19
Level 1. 달리기 경주  (0) 2023.04.17
Level 2. [3차] 파일명 정렬  (0) 2023.04.16
Level 2. 괄호 회전하기  (0) 2023.04.15
profile

Make Unreal REAL.

@diesuki4

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그