본문 바로가기
문제/프로그래머스

c++ 프로그래머스_"방문 길이"

by 나 진짜 못차마 2023. 6. 13.
728x90

https://programmers.co.kr/learn/courses/30/lessons/49994

 

프로그래머스

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

programmers.co.kr

 

set을 이용하여 해결하였다.

경로는 현재 좌표 + 이동 좌표 를

string으로 묶어 set에 집어넣어

만약 set에 있다면 이미 지나온 경로니까

그냥 진행하고

set에 없다면 처음 이동한 경로니까

추가해주었다.

 

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

bool is_in(int x,int y){
    if(x < -5 || y < -5 || x > 5 || y > 5)
        return false;
    return true;
}

int solution(string dirs) {
    int answer = 0;
    
    set<string> st;
    
    int x = 0 , y = 0;
    for(int i=0;i<dirs.length();i++){
        
        char dir = dirs[i];
        
        int next_x = x, next_y = y;
        if(dir == 'U'){
            next_y += 1;
        }else if(dir == 'D'){
            next_y -= 1;
        }else if(dir == 'R'){
            next_x += 1;
        }else{
            next_x -= 1;
        }        
        
        if(is_in(next_x,next_y)){
            string path_1 = to_string(x) + to_string(y) + to_string(next_x)+to_string(next_y);    
            string path_2 = to_string(next_x)+to_string(next_y) + to_string(x) + to_string(y);
            
            x = next_x , y = next_y;
            if(st.find(path_1) != st.end() ||
                st.find(path_2) != st.end())
                continue;
            
            st.insert(path_1);
            answer ++;
        }
    }
    
    return answer;
}

728x90