728x90
반응형
🔗 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/49994
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
728x90
👩💻 코드
#include <string>
#include <vector>
#include <map>
#include <utility>
#include <algorithm>
#include <iostream>
using namespace std;
int solution(string dirs) {
int answer = 0;
int x = 0;
int y = 0;
map<char, pair<int, int>> directions = {{'U', {0, 1}}, {'D', {0, -1}}, {'R', {1, 0}}, {'L', {-1, 0}}};
vector<pair<pair<int, int>, pair<int, int>>> paths;
for(auto d : dirs){
int newX = x + directions[d].first;
int newY = y + directions[d].second;
if (newX < -5 || newX > 5 || newY < -5 || newY > 5) {
continue;
}
if(find(paths.begin(), paths.end(), make_pair(make_pair(x,y), make_pair(newX, newY))) == paths.end()
&& find(paths.begin(), paths.end(), make_pair(make_pair(newX,newY), make_pair(x, y))) == paths.end()){
answer++;
}
paths.push_back(make_pair(make_pair(x, y), make_pair(newX, newY)));
x = newX;
y = newY;
}
return answer;
}
📝 풀이
처음에 key는 방향 value는 좌표값을 가진 방향 map을 정의합니다.
dirs의 문자열의 문자로 방향을 확인하여 도착 좌표를 계산합니다.
좌표를 벗어나는 경우에는 무시하기 위해 continue를 합니다.
기존에 출발 좌표와 도착 좌표 쌍과 반대로 되어 있는 쌍이 없다면(= 새로운 길) answer을 증가시킵니다.
출발 좌표와 도착 좌표를 쌍으로 paths에 저장합니다.
현재 좌표 정보를 업데이트 해줍니다.
최종적으로 answer을 return 합니다.
728x90
반응형
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 땅따먹기 (0) | 2024.08.18 |
---|---|
[프로그래머스] 더 맵게 (0) | 2024.08.16 |
[프로그래머스] 뒤에 있는 큰 수 찾기 (1) | 2024.08.16 |
[프로그래머스] 롤케이크 자르기 (0) | 2024.08.15 |
[프로그래머스] 모음사전 (0) | 2024.08.15 |