캐릭터는 좌표평면의 (0, 0) 위치에서 시작합니다. 좌표평면의 경계는 왼쪽 위(-5, 5), 왼쪽 아래(-5, -5), 오른쪽 위(5, 5), 오른쪽 아래(5, -5)로 이루어져 있습니다.
예를 들어, "ULURRDLLU"로 명령했다면
1번 명령어부터 7번 명령어까지 다음과 같이 움직입니다.
8번 명령어부터 9번 명령어까지 다음과 같이 움직입니다.
이때, 우리는 게임 캐릭터가 지나간 길 중캐릭터가 처음 걸어본 길의 길이를 구하려고 합니다. 예를 들어 위의 예시에서 게임 캐릭터가 움직인 길이는 9이지만, 캐릭터가 처음 걸어본 길의 길이는 7이 됩니다. (8, 9번 명령어에서 움직인 길은 2, 3번 명령어에서 이미 거쳐 간 길입니다)
단, 좌표평면의 경계를 넘어가는 명령어는 무시합니다.
예를 들어, "LULLLLLLU"로 명령했다면
1번 명령어부터 6번 명령어대로 움직인 후, 7, 8번 명령어는 무시합니다. 다시 9번 명령어대로 움직입니다.
이때 캐릭터가 처음 걸어본 길의 길이는 7이 됩니다.
명령어가 매개변수 dirs로 주어질 때, 게임 캐릭터가 처음 걸어본 길의 길이를 구하여 return 하는 solution 함수를 완성해 주세요.
제한사항
dirs는 string형으로 주어지며, 'U', 'D', 'R', 'L' 이외에 문자는 주어지지 않습니다.
dirs의 길이는 500 이하의 자연수입니다.
입출력 예dirsanswer
"ULURRDLLU"
7
"LULLLLLLU"
7
입출력 예 설명
입출력 예 #1 문제의 예시와 같습니다.
입출력 예 #2 문제의 예시와 같습니다.
문제풀이
방문 했던 길을 저장할 History 클래스를 만든 후 첫 방문인지 체크 후 첫 방문이면
History Set에 저장 첫 방문이 아니면 cursor에 이동처리만 하고 저장하지 않는다.
소스코드
Map<String, Integer> cursor;
Set<History> historyList;
int POSITIVE_RANGE = 5;
int NEGATIVE_RANGE = -5;
int answer = 0;
public int solution(String dirs) {
cursor = new HashMap<>();
cursor.put("x", 0);
cursor.put("y", 0);
historyList = new HashSet<>();
for (int i = 0; i < dirs.length(); i++) {
move(dirs.charAt(i));
}
return answer;
}
class History {
int x;
int y;
int distX;
int distY;
public History (int x, int y, int distX, int distY) {
this.x = x;
this.y = y;
this.distX = distX;
this.distY = distY;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof History)) {
return false;
}
if (obj == this) {
return true;
}
History compare = (History) obj;
return (this.x == compare.x && this.y == compare.y && this.distX == compare.distX && this.distY == compare.distY)
|| (this.x == compare.distX && this.y == compare.distY && this.distX == compare.x && this.distY == compare.y);
}
}
public void move(char command) {
int currentX = cursor.get("x");
int currentY = cursor.get("y");
switch (command) {
case 'U':
int up = currentY + 1;
if (up <= POSITIVE_RANGE) {
cursor.put("y", up);
checkFirst(new History(currentX, currentY, currentX, up));
}
break;
case 'D':
int down = currentY - 1;
if (down >= NEGATIVE_RANGE) {
cursor.put("y", down);
checkFirst(new History(currentX, currentY, currentX, down));
}
break;
case 'R':
int right = currentX + 1;
if (right <= POSITIVE_RANGE) {
cursor.put("x", right);
checkFirst(new History(currentX, currentY, right, currentY));
}
break;
case 'L':
int left = currentX - 1;
if (left >= NEGATIVE_RANGE) {
cursor.put("x", left);
checkFirst(new History(currentX, currentY, left, currentY));
}
break;
}
}
private void checkFirst(History history) {
boolean isNotInclude = true;
for (History h : historyList) {
if (h.equals(history)) {
isNotInclude = false;
}
}
if (isNotInclude) {
historyList.add(history);
answer++;
}
}