[문제]
게임 캐릭터를 4가지 명령어를 통해 움직이려 합니다. 명령어는 다음과 같습니다.
U: 위쪽으로 한 칸 가기
D: 아래쪽으로 한 칸 가기
R: 오른쪽으로 한 칸 가기
L: 왼쪽으로 한 칸 가기
캐릭터는 좌표평면의 (0, 0) 위치에서 시작합니다. 좌표평면의 경계는 왼쪽 위(-5, 5), 왼쪽 아래(-5, -5), 오른쪽 위(5, 5), 오른쪽 아래(5, -5)로 이루어져 있습니다.
이때, 우리는 게임 캐릭터가 지나간 길 중 캐릭터가 처음 걸어본 길의 길이를 구하려고 합니다. 예를 들어 위의 예시에서 게임 캐릭터가 움직인 길이는 9이지만, 캐릭터가 처음 걸어본 길의 길이는 7이 됩니다. (8, 9번 명령어에서 움직인 길은 2, 3번 명령어에서 이미 거쳐 간 길입니다)
단, 좌표평면의 경계를 넘어가는 명령어는 무시합니다.
명령어가 매개변수 dirs로 주어질 때, 게임 캐릭터가 처음 걸어본 길의 길이를 구하여 return 하는 solution 함수를 완성해 주세요.
[제한조건]
- dirs는 string형으로 주어지며, 'U', 'D', 'R', 'L' 이외에 문자는 주어지지 않습니다.
- dirs의 길이는 500 이하의 자연수입니다.
| dirs | answer |
| "ULURRDLLU" | 7 |
| "LULLLLLLU" | 7 |
[풀이]
class Solution {
public int solution(String dirs) {
int answer = 0;
int[][] upAndDown = new int[11][10]; //x축(고정), y축
int[][] leftAndRight = new int[10][11]; //x축, y축(고정)
int current_x = 0;
int current_y = 0;
for(char c: dirs.toCharArray()) {
switch(c){
case 'U':
if(current_y == 5) break;
if(upAndDown[current_x + 5][current_y + 5] == 0){
upAndDown[current_x + 5][current_y + 5] = 1;
++answer;
}
++current_y;
break;
case 'D':
if(current_y == -5) break;
--current_y;
if(upAndDown[current_x + 5][current_y + 5] == 0){
upAndDown[current_x + 5][current_y + 5] = 1;
++answer;
}
break;
case 'R':
if(current_x == 5) break;
if(leftAndRight[current_x + 5][current_y + 5] == 0){
leftAndRight[current_x + 5][current_y + 5] = 1;
++answer;
}
++current_x;
break;
case 'L':
if(current_x == -5) break;
--current_x;
if(leftAndRight[current_x + 5][current_y + 5] == 0){
leftAndRight[current_x + 5][current_y + 5] = 1;
++answer;
}
break;
}
}
return answer;
}
}
import java.util.*;
class Solution {
// 좌표평면을 벗어나는지 체크하는 메서드
public static boolean isValidMove(int nx, int ny) {
return 0 <= nx && nx < 11 && 0 <= ny && ny < 11;
}
//다음 좌표 결정을 위한 해쉬맵 생성
private static final HashMap<Character, int[]> location = new HashMap<>();
private static void initLocation() {
location.put('U', new int[]{0, 1});
location.put('D', new int[]{0, -1});
location.put('L', new int[]{1, 0});
location.put('R', new int[]{-1, 0});
}
public int solution(String dirs) {
initLocation();
//시작 시점
int x = 5;
int y = 5;
HashSet<String> answer = new HashSet<>(); //겹치는 좌표 1개로 처리
for(int i = 0; i < dirs.length(); ++i) {
int[] offset = location.get(dirs.charAt(i));
int nx = x + offset[0];
int ny = y + offset[1];
//벗어난 좌표 인정X
if(!isValidMove(nx, ny)) continue;
answer.add(x + " " + y + " " + nx + " " + ny);
answer.add(nx + " " + ny + " " + x + " " + y);
x = nx;
y = ny;
}
return answer.size()/2;
}
}
[문제 링크]
https://school.programmers.co.kr/learn/courses/30/lessons/49994
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
'문제 풀이 > 프로그래머스' 카테고리의 다른 글
| [프로그래머스 / 2017 팁스타운] 짝지어 제거하기 (1) | 2025.03.18 |
|---|---|
| [프로그래머스 / 월간 코드 챌린지 시즌2] 괄호 회전하기 (1) | 2025.03.18 |
| [프로그래머스 / 2019 KAKAO BLIND RECRUITMENT]실패율 (1) | 2025.03.17 |
| [프로그래머스 / 연습문제] 행렬의 곱셈 (0) | 2025.03.17 |
| [프로그래머스 / 월간 코드 챌린지 시즌1] 두 개 뽑아서 더하기 (1) | 2025.03.10 |