본문 바로가기
[알고리즘 + 자료구조]/[프로그래머스]

프로그래머스 방문 길이 C++

by Hevton 2023. 8. 12.
반응형

 

 

다른 분들의 풀이도 유사했다.

#include <string>
#include <vector>
#include <set>
using namespace std;

int mx[4] = {1, 0, -1, 0}; // 상우하좌. 반대방향 처리를 위해 1칸씩 경계로.
int my[4] = {0, 1, 0, -1}; // 상우하좌


// 두 좌표를 쓰는 대신에 하나의 숫자값을 써도 되는 문제긴 하다

bool outOfBounds(int x, int y, int d) {
    
    int xx = x + mx[d];
    int yy = y + my[d];
    
    if(xx < -5 || xx > 5 || yy < -5 || yy > 5)
        return true;
    
    return false;
}

int solution(string dirs) {
    int answer = 0;
    
    int len = dirs.length();
    
    set<pair<pair<int, int>, int>> cordi;
    vector<int> directions;
    
    
    for(int i = 0; i < len; i++) {
        switch(dirs[i]) {
            case 'U':
                directions.push_back(0);
                break;
            case 'R':
                directions.push_back(1);
                break;
            case 'D':
                directions.push_back(2);
                break; 
            case 'L':
                directions.push_back(3);
                break;                
        }
    }
    
    int x = 0, y = 0;    
    
    for(auto d : directions) {
        
        if(outOfBounds(x, y, d))
            continue;
        else {
            
            cordi.insert({{x, y}, d});

            x += mx[d];
            y += my[d];
            
            // 반대 방향도
            cordi.insert({{x, y}, (d + 2) % 4});

        }
        
    }
    
    return cordi.size() / 2;
}

 

 

 

반응형