Algorithm
[프로그래머스] 공원 산책(Java)
거북목을 가진 김기린
2024. 4. 27. 00:31
728x90
반응형
문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
시작 지점(S)에서 주어진 쿼리에 따라서 움직이고 난 후의 위치를 리턴하는 문제이다.
움직임을 위해 park 배열을 2차원 배열로 변경해주고, 시작 지점의 좌표 값을 획득한다.
현재 쿼리를 통해 방향과 얼만큼 움직일지 확인하고
현재 위치(r, c)에서 해당 방향으로 한칸씩 움직였다고 가정했을 때, 그 위치가 맵을 벗어났거나 장애물이 있다면 바로 넘겨줌
이 점을 while 반복과 flag를 사용해 구현한다.
이상이 없다면, 현재 위치 값을 갱신해주고, 다음 쿼리를 진행한다.
코드
import java.util.*;
class Solution {
static int N, M, r, c;
static char[][] arr;
static int[] dr = {-1, 0, 1, 0};
static int[] dc = {0, 1, 0, -1};
public int[] solution(String[] park, String[] routes) {
StringTokenizer st;
N = park.length;
M = park[0].length();
int queryLen = routes.length;
arr = new char[N][M];
for(int i = 0 ; i < N ; i ++){
String s = park[i];
for(int j = 0 ; j < M ; j ++){
char cur = s.charAt(j);
if(cur == 'S'){
r = i;
c = j;
}
arr[i][j] = cur;
}
}
for(int i = 0 ; i < queryLen ; i ++){
st = new StringTokenizer(routes[i]);
String s = st.nextToken();
int d = direction(s);
int n = Integer.parseInt(st.nextToken());
// 움직임
int nr = r;
int nc = c;
boolean flag = true;
for(int j = 0 ; j < n ; j ++){
nr += dr[d];
nc += dc[d];
if(!isValid(nr, nc) || arr[nr][nc] == 'X'){
flag = false;
break;
}
}
if(!flag) continue;
r = nr;
c = nc;
}
return new int[]{r, c};
}
static int direction(String s){
if(s.equals("N")) return 0;
else if(s.equals("E")) return 1;
else if(s.equals("S")) return 2;
else return 3;
}
static boolean isValid(int nr, int nc){
return (nr>=0 && nr<N && nc>=0 && nc<M);
}
}
728x90
반응형