본문 바로가기
Dev/Algorithm

[프로그래머스] 공원 산책 - Java

by VIPeveloper 2024. 5. 20.
반응형

문제

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

 

생각

  • 수도코드를 작성한 대로 코드를 작성하는 것에 점차 익숙해지고 있다.
  • BFS 에 대한 개념을 묻는 문제인 것 같고, 어렵지 않게 해결할 수 있었다.

1. dh, dw 배열 생성
2. 2차원 배열 생성해서 채우기
3. routes 를 순회하며 해당 명령어를 수행할 수 있는지 판단.
4. 가능할 경우 이동
5. 끝난 후 위치 반환

코드

public class Main {
    public static void main(String[] args) {
        System.out.println(solution(new String[] {"SOO","OOO","OOO"},new String[]{"E 2","S 2","W 1"}));
        System.out.println(solution(new String[] {"OSO","OOO","OXO","OOO"},new String[]{"E 2","S 3","W 1"}));
    }

    // 1. dh, dw 배열 생성 - 상,하,좌,우
    public static int[] dh = {-1,1,0,0};
    public static int[] dw = {0,0,-1,1};

    public static int[] solution(String[] park, String[] routes) {
        int curH = 0;
        int curW = 0;
        // 2. 2차원 배열 생성해서 채우기
        String [][] map = new String[park.length][park[0].length()];
        for (int i = 0; i < park.length; i++) {
            String [] row = park[i].split("");
            for (int j = 0; j < park[i].length(); j++) {
                map[i][j] = row[j];
                if("S".equals(map[i][j])){
                    curH = i;
                    curW = j;
                }
            }
        }
        // 3. routes 를 순회하며 해당 명령어를 수행할 수 있는지 판단.
        for (int i = 0; i < routes.length; i++) {
            String dir = routes[i].split(" ")[0];
            int dir_idx = 0;
            if("S".equals(dir)) dir_idx = 1;
            else if("E".equals(dir)) dir_idx = 3;
            else if("W".equals(dir)) dir_idx = 2;
            int distance = Integer.valueOf(routes[i].split(" ")[1]);
            boolean correct_cmd = pandan(park, distance, dir_idx, curW, curH, map);
            if(correct_cmd){
                int nh = curH + dh[dir_idx]*distance;
                int nw = curW + dw[dir_idx]*distance;
                map[curH][curW] = "O";
                map[nh][nw] = "S";
                curH = nh;
                curW = nw;
            }
        }

        return new int[]{curH,curW};
    }

    // 하나씩 길이 늘려가며 해당되는지 안되는지 판단
    private static boolean pandan(String[] park, int distance, int dir_idx, int curW, int curH, String[][] map) {
        for (int j = 1; j <= distance; j++) {
            int nw = dw[dir_idx]*j + curW;
            int nh = dh[dir_idx]*j + curH;
            if (0> nw || nw >= park[0].length() || 0> nh || nh >= park.length || "X".equals(map[nh][nw])) {
                return false;
            }
        }
        return true;
    }
}

다른 사람 코드

다른 사람의 코드도 비슷하다.

반응형