[알고리즘] 프로그래머스 49994 (2)

은개·2025년 8월 22일

[CS] 알고리즘

목록 보기
16/21

풀이

0. 현재 -> 다음 경로가 유효한지 체크
1. 현재 -> 다음, 다음 -> 현재로 이동한 경로가 이미 있는지 확인
2-1. 없으면 {(현재, 다음), (다음, 현재)} 좌표를 저장하고 다음으로 이동
2-2. 있으면 저장하지 않고 다음으로 이동
3. 방문한 경로의 수를 반환

정답

#include <string>
#include <vector>
#include <set>
#include <iostream>

using namespace std;

bool checkWall(pair<int, int> next) {
    if (next.first > 5 || next.first < -5 
        || next.second > 5 || next.second < -5) {
        return true;
    }
    
    return false;
}

int solution(string dirs) {
    int answer = 0;
    
    pair<int, int> current = {0, 0};
    
    // [{{0, 0}, {0, 0}}, ...]
    set<pair<pair<int, int>, pair<int, int>>> visitedPath; 
    
    for (char dir : dirs) {
        pair<int, int> next = current;
        
        if (dir == 'U') { // y++
            next.second = current.second + 1;
        } else if (dir == 'D') { //y--
            next.second = current.second - 1;
        } else if (dir == 'R') { // x++
            next.first = current.first + 1;
        } else if (dir == 'L') { // x--
            next.first = current.first - 1;
        } 
        
        if (!checkWall(next)) {
            // 방문하지 않은 경로이면 방문 경로에 저장
            if (visitedPath.find({next, current}) == visitedPath.end() 
                && visitedPath.find({current, next}) == visitedPath.end()) {
                visitedPath.insert({next, current});
                visitedPath.insert({current, next});
            }
            
            current = next;
        }
    }
    
    for (auto path: visitedPath) {
        pair<int, int> current = path.first;
        pair<int, int> next = path.second;
    }
    
    answer = visitedPath.size() / 2;
    return answer;
}

0개의 댓글