

-Code
import java.util.*;
class Solution {
static class Pos {
int row, col;
public Pos(int row, int col) {
this.row = row;
this.col = col;
}
public void set(int row, int col) {
this.row = row;
this.col = col;
}
}
// 각 번호 위치 셋팅
static Pos[] numPos = new Pos[10];
static {
numPos[0] = new Pos(4, 2);
int n = 1;
for(int r = 1; r < 4; r++) {
for(int c = 1; c < 4; c++) {
numPos[n++] = new Pos(r, c);
}
}
}
public String solution(int[] numbers, String hand) {
StringBuilder answer = new StringBuilder();
// 초반 왼쪽과 오른쪽 손 위치 초기화
Pos left = new Pos(4, 1);
Pos right = new Pos(4, 3);
// 번호에 따른 손 위치 변경 및 결과 저장
for(int num : numbers) {
Pos nextPos = numPos[num];
// 중간 위치의 숫자로 가야하는 경우
if (nextPos.col == 2) {
// 다음 위치까지 왼손과 오른손 각각 거리 계산
int leftDist = getDist(left, nextPos);
int rightDist = getDist(right, nextPos);
// 거리에 따른 값 저장
if (leftDist < rightDist) {
answer.append("L");
left.set(nextPos.row, nextPos.col);
} else if (leftDist > rightDist) {
answer.append("R");
right.set(nextPos.row, nextPos.col);
} else {
// 같은 거리인 경우 주손을 이동
answer.append(hand.equals("right") ? "R" : "L");
if (hand.equals("right")) {
right.set(nextPos.row, nextPos.col);
} else {
left.set(nextPos.row, nextPos.col);
}
}
} else {
// 왼쪽과 오른쪽은 각 손만 가능하므로 저장 및 위치 변경
if (nextPos.col == 1) {
answer.append("L");
left.set(nextPos.row, nextPos.col);
} else {
answer.append("R");
right.set(nextPos.row, nextPos.col);
}
}
}
return answer.toString();
}
// 거리 구하기
private int getDist(Pos nowPos, Pos nextPos) {
int nowRow = nowPos.row;
int nowCol = nowPos.col;
int nextRow = nextPos.row;
int nextCol = nextPos.col;
int rowGap = nowRow - nextRow;
int colGap = nowCol - nextCol;
return Math.abs(rowGap) + Math.abs(colGap);
}
}'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [프로그래머스/Java] 바탕화면 정리 (0) | 2026.03.18 |
|---|---|
| [백준/Java] 35261번 피갤컵 들어왔으면 이 글부터 봐라 (0) | 2026.03.18 |
| [프로그래머스/Java] 달리기 경주 (0) | 2026.03.17 |
| [백준/Java] 3010번 페그 (0) | 2026.03.17 |
| [프로그래머스/Java] 신규 아이디 추천 (0) | 2026.03.17 |