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

codesver·2023년 7월 4일
0

Programmers

목록 보기
30/30
post-thumbnail

📌 Problem

공원은 O와 X으로 이루어진 R x C 크기의 2차원 배열 형태이다. O는 지나다닐 수 있는 공간이고 X는 장애물이어서 지나다닐 수 없다. 특정 위치 S에 로복 개를 두고 명령을 입력하여 이동한다. 공원과 로봇 개의 정보, 그리고 명령들이 주어졌을 때 로봇 개의 최종적인 위치를 출력하면된다.

각각의 명령은 방향(N E S W)과 거리(1 ~ 9)으로 이루어져 있다. 명령을 실행했을 때 공원 밖으로 나가거나 중간에 장애물(X)를 만나면 해당 명령은 실행하지 않는다.

📌 Code

class Solution {

    Map<Character, Point> moves = new HashMap<>() {{
        put('N', new Point(-1, 0));
        put('E', new Point(0, 1));
        put('S', new Point(1, 0));
        put('W', new Point(0, -1));
    }};

    int ROW, COL;
    Point robot;
    boolean[][] map;

    public int[] solution(String[] park, String[] routes) {
        init(park);
        walk(routes);
        return new int[]{robot.x, robot.y};
    }

    private void init(String[] park) {
        ROW = park.length;
        COL = park[0].length();

        robot = new Point(0, 0);
        map = new boolean[ROW][COL];

        for (int r = 0; r < ROW; r++) {
            for (int c = 0; c < COL; c++) {
                char type = park[r].charAt(c);
                if (type == 'S') robot = new Point(r, c);
                map[r][c] = type != 'X';
            }
        }
    }

    private void walk(String[] routes) {
        loop:
        for (String route : routes) {
            Point direction = moves.get(route.charAt(0));
            int distance = Integer.parseInt(route.substring(2));

            int nextRow = robot.x + direction.x * distance;
            int nextCol = robot.y + direction.y * distance;

            if (robot.x != nextRow) {
                if (!(0 <= nextRow && nextRow < ROW)) continue;
                for (int r = Math.min(robot.x, nextRow); r <= Math.max(robot.x, nextRow); r++)
                    if (!map[r][robot.y]) continue loop;
            } else if (robot.y != nextCol) {
                if (!(0 <= nextCol && nextCol < COL)) continue;
                for (int c = Math.min(robot.y, nextCol); c <= Math.max(robot.y, nextCol); c++)
                    if (!map[robot.x][c]) continue loop;
            }
            robot.x = nextRow;
            robot.y = nextCol;
        }
    }
}
profile
Hello, Devs!

0개의 댓글