https://school.programmers.co.kr/learn/courses/30/lessons/49994
필요한것 :
현재 위치를 나타낼 2차원 좌표 변수
입력대로 이동했을 때 유효한 이동인지 체크하고 이동하는 함수
이동을 저장할 컨테이너이동을 저장할 컨테이너는 출발좌표, 도착좌표, bool을 담고있는 map이다.
이동함수에선 알파벳에 맞게 이동했을 때 범위를 벗어나는지 체크한다.
이미 지나간 선이면 좌표만 갱신해준다.
처음지나가는 선이면 시작점과 끝점, 끝점과 시작점을 모두 true해주고 ( 방향 상관없이 중복 체크 ) answer++한다.
#include <string>
#include <map>
using namespace std;
int answer = 0;
map<pair<pair<int,int>,pair<int,int>>,bool> visited;
void Move(int& x, int& y, char m)
{
int ex = x;
int ey = y;
if(m == 'U')
{
if(y + 1 > 5)
return;
ey++;
}
if(m == 'D')
{
if(y - 1 < -5)
return;
ey--;
}
if(m == 'R')
{
if(x + 1 > 5)
return;
ex++;
}
if(m == 'L')
{
if(x - 1 < -5)
return;
ex--;
}
if(visited[make_pair(make_pair(x,y), make_pair(ex,ey))] == true)
{
x = ex;
y = ey;
return;
}
visited[make_pair(make_pair(x,y), make_pair(ex,ey))] = true;
visited[make_pair(make_pair(ex,ey), make_pair(x,y))] = true;
x = ex;
y = ey;
answer++;
}
int solution(string dirs) {
int x = 0;
int y = 0;
for(char c : dirs)
Move(x,y,c);
return answer;
}
#include <string>
#include <set>
using namespace std;
int toIdx(char ch){
switch(ch){
case 'R': return 0;
case 'L': return 1;
case 'U': return 2;
case 'D': return 3;
}
}
int solution(string dirs) {
char ch;
int answer = 0,i, x=0,y=0,ty,tx,dy[]={0,0,1,-1},dx[]={1,-1,0,0},idx,a,b;
set<pair<int,int>> ans;
for(i=0;i<dirs.length();i++) {
ch = dirs[i];
idx = toIdx(ch);
tx = x + dx[idx], ty = y + dy[idx];
if(!(-5 <= ty && ty <= 5 && -5 <= tx && tx <= 5)) continue;
a = x*10000+y;
x = tx, y = ty;
b = x*10000+y;
if(ans.find({a,b}) == ans.end() && ans.find({b,a}) == ans.end())
ans.insert({a,b});
}
return answer = (int)ans.size();
}
set을 사용했다.
dy dx배열을 미리 선언해놓고 알파벳을 숫자로 바꿔서 이동할 좌표를 구한다.
이동할 좌표의 유효성을 검사 후 set에 원소를 추가하는데
x*10000 + y를 해서 굳이 이중으로 pair를 사용 안하고 좌표를 저장했다.
ans.insert({b,a})도 추가하면 더 완벽할 것 같다.