09009

[프로그래머스 lv1] 공원 산책 본문

Algorithm
[프로그래머스 lv1] 공원 산책
09009

문제 보기

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

문제 해결

시작점 'S'를 찾아서 시작 좌표(cx, cy)를 저장해둔다.

주의할 점은 한 칸씩 이동할 때마다 문제에서 주어진 조건에 적합하지 않은지 판단해야 하는 식을 작성해야 한다.

     
            while (count > 0) {
                count--;
                nx += map.get(direction)[0];
                ny += map.get(direction)[1];
                if (nx < 0 || nx >= m || ny < 0 || ny >= n) {
                    flag = false;
                    break;
                }
                if (park[nx].charAt(ny) == 'X') {
                    flag = false;
                    break;
                }  
            }

 

if문에 해당할 경우 false로 설정하고 두 if 조건문에 걸리지 않았을 경우에만 이동하도록 설정한다.

 

 

전체 소스 코드

import java.util.*;
class Solution {
    public int[] solution(String[] park, String[] routes) {
        int[] answer = new int[2];
        
        Map<String, int[]> map = new HashMap<>();
        map.put("N", new int[]{-1, 0}); 
        map.put("S", new int[]{1, 0});
        map.put("W", new int[]{0, -1});
        map.put("E", new int[]{0, 1});
        
        int m = park.length;
        int n = park[0].length();
           
        int cx = 0;
        int cy = 0;
        for (int i=0; i<m; i++) {
            for (int j=0; j<n; j++) {
                if (park[i].charAt(j) == 'S') {
                    cx = i;
                    cy = j;
                    break;
                }
            }
        }
        
        for (int i=0; i<routes.length; i++) {
            String direction = routes[i].split(" ")[0];
            int count = Integer.parseInt(routes[i].split(" ")[1]);
            
            int nx = cx;
            int ny = cy;
            
            boolean flag = true;
            
            while (count > 0) {
                count--;
                nx += map.get(direction)[0];
                ny += map.get(direction)[1];
                if (nx < 0 || nx >= m || ny < 0 || ny >= n) {
                    flag = false;
                    break;
                }
                if (park[nx].charAt(ny) == 'X') {
                    flag = false;
                    break;
                }  
            }
            
            if (flag) {
                cx = nx;
                cy = ny;
            }
        }
        
        answer[0] = cx;
        answer[1] = cy;
        return answer;
    }
}