-
프로그래머스 LV1 - 공원 산책STUDY/ALGORITHM 2025. 2. 12. 22:50
이 문제는 커다란 함정이 숨어있다.
그것은 그리드에서 (0,0)의 좌표가 왼쪽 위고, (h-1,w-1) 이 왼쪽 아래라는 것.
그냥 위아래 뒤집어서 생각하고, South 또는 North로 이동할때 Y 값을 반대로 적용해주면 특별히 신경쓸 일이 없다.
좌표평면 위를 이동하는 문제에서 0,0의 위치도 당연시 하면 안된다는 경각심을 주는 문제인것도 같다.
사실 그걸 제외하면 어려운 문제는 확실히 아니었다.
다 풀고나서 아차 싶었던 점이 있다.
나는 무의식적으로 재귀함수로 풀었는데, 만약 이동거리의 범위가 "1<=n<= 10" 이 아니었다면,
그리고 park의 크기가 엄청나게 컸다면 재귀함수 깊이문제가 발생했을 수도 있다.
제한사항을 보고 다시보자....
import java.util.*; class Solution { private int w,h; private int[] start; private Map<String,int[]> offsetMap; private boolean[][] isWall; public int[] solution(String[] park, String[] routes) { init(park); for (String route : routes) { String[] s = route.split(" "); String d = s[0]; int r = Integer.parseInt(s[1]); int[] offset = offsetMap.get(d); boolean isPossible = recursive(offset, start[0], start[1], r); if(isPossible){ for (int i = 0; i < r; i++) { start[0] += offset[0]; start[1] += offset[1]; } } } return start; } private void init(String[] park){ h = park.length; w = park[0].length(); offsetMap = new HashMap<>(); isWall = new boolean[h][w]; offsetMap.put("E", new int[]{0,1}); offsetMap.put("W", new int[]{0,-1}); offsetMap.put("N", new int[]{-1,0}); //상하 반대로되어있음. offsetMap.put("S", new int[]{1,0}); for (int i = 0; i < h; i++) { String string = park[i]; for (int j = 0; j < w; j++) { char al = string.charAt(j); if(al == 'O' || al == 'S'){ if(al == 'S'){ start = new int[]{i,j}; } isWall[i][j] = false; continue; } isWall[i][j] = true; } } } private boolean isValid(int y, int x){ if(y > h - 1 || x > w -1 || y < 0 || x < 0) return false; return true; } private boolean recursive(int[] offset, int curY, int curX, int count){ if(!isValid(curY, curX) || isWall[curY][curX]) return false; if(count == 0 ) return true; return recursive(offset, curY + offset[0], curX + offset[1], count - 1); } }'STUDY > ALGORITHM' 카테고리의 다른 글
프로그래머스 LV1 - 택배 상자 꺼내기 (0) 2025.02.17 프로그래머스 LV1 - 달리기 경주 (1) 2025.02.12 프로그래머스 LV1 - 대충 만든 자판 (1) 2025.02.11 프로그래머스 LV2 - 지게차와 크레인 (0) 2025.02.11 프로그래머스 LV2 - 충돌위험 찾기 (0) 2025.02.10