프로그래머스 - 캐릭터의 좌표

남궁진 (jinvicky)·2026년 4월 24일

Problem


https://school.programmers.co.kr/learn/courses/30/lessons/120861

Solution


이 문제의 핵심은 내가 중앙에 있다는 것이다. 그래서 절반만 이동해도 4방향 끝단에 도달할 수 있기 때문에 사전에 limit을 걸어야 한다.

3개 이상의 조건이면 swtich로 풀라고 배웠지만 매번 break;를 1줄을 위해 거는 것이 귀찮아서 else-if로도 풀었다.

Code


class Solution {
    public int[] solution(String[] keyinput, int[] board) {
        int[] answer = new int[2];
        
        int limitX = board[0] / 2;
        int limitY = board[1] / 2;
        
        for(int i = 0; i < keyinput.length; i++) {
            int nextX = answer[0];
            int nextY = answer[1];
            
            String dir = keyinput[i];
            
            if(dir.equals("left")) {
                nextX--;
            } else if (dir.equals("right")){
                nextX++;
            } else if (dir.equals("up")){
                nextY++;
            } else if (dir.equals("down")){
                nextY--;
            }
            
            if(Math.abs(nextX) <= limitX && Math.abs(nextY)  <= limitY) {
                answer[0] = nextX;
                answer[1] = nextY;
            }
        
        }
        
        return answer;
    }
}
profile
문제를 차근차근 하나씩 해결하려고 합니다:)

0개의 댓글