반갑습니다!

[프로그래머스] 방문 길이 본문

알고리즘 문제 풀이

[프로그래머스] 방문 길이

김덜덜이 2020. 4. 17. 16:17
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr

풀이

문제의 조건만 잘 유의하면 어렵지않게 풀 수 있다. Set을 사용하여 경로의 중복을 체크하였는다. 그런데 이 문제는 범위가 워낙 작아서 굳이 Set을 사용하지 않고 배열로도 해결할 수 있을 것으로 보인다.

코드

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

bool inRange(int x, int y) {
    return (-5 <= x && x <= 5) && (-5 <= y && y <= 5);
}

int solution(string dirs) {
    int answer = 0;
    set<pair<pair<int, int>, pair<int, int>>> s;
    int x = 0;
    int y = 0;
    for (char c : dirs) {
        if (c == 'U') {
            if (inRange(x, y + 1)) {
                if (s.find({ {x, y}, {x, y + 1} }) == s.end()) {
                    answer++;
                    s.insert({ {x, y}, {x, y + 1} });
                    s.insert({ {x, y + 1}, {x, y} });
                }
                y++;
            }
        }
        else if (c == 'L') {
            if (inRange(x - 1, y)) {
                if (s.find({ {x, y}, {x - 1, y} }) == s.end()) {
                    answer++;
                    s.insert({ {x, y}, {x - 1, y} });
                    s.insert({ {x - 1, y}, {x, y} });
                }
                x--;
            }
        }
        else if (c == 'R') {
            if (inRange(x + 1, y)) {
                if (s.find({ {x, y}, {x + 1, y} }) == s.end()) {
                    answer++;
                    s.insert({ {x, y}, {x + 1, y} });
                    s.insert({ {x + 1, y} , {x, y} });
                }
                x++;
            }
        }
        else if (c == 'D') {
            if (inRange(x, y - 1)) {
                if (s.find({ {x, y}, {x, y - 1} }) == s.end()) {
                    answer++;
                    s.insert({ {x, y}, {x, y - 1} });
                    s.insert({ {x, y - 1}, {x, y} });
                }
                y--;
            }
        }
    }
    return answer;
}