

-Code
import java.util.*;
class Solution {
// 위치 정보를 저장할 클래스
static class Pos {
int row, col;
public Pos(int row, int col) {
this.row = row;
this.col = col;
}
// 이동시 현재 위치에 더해주는 메소드
public void move(int dRow, int dCol) {
this.row += dRow;
this.col += dCol;
}
// 위치 정보를 배열로 반환
public int[] toArray() {
return new int[] {this.row, this.col};
}
}
// 방향을 바로 알기위한 map
static Map<Character, int[]> dirMap = Map.of(
'N', new int[] {-1, 0},
'S', new int[] {1, 0},
'W', new int[] {0, -1},
'E', new int[] {0, 1}
);
public int[] solution(String[] park, String[] routes) {
// 시작점 찾기
Pos now = null;
for (int r = 0; r < park.length; r++) {
for (int c = 0; c < park[r].length(); c++) {
if (park[r].charAt(c) == 'S') {
now = new Pos(r, c);
break;
}
}
if (now != null) {
break;
}
}
// 명령어에 따른 이동
for (String move : routes) {
StringTokenizer st = new StringTokenizer(move);
// 이동 방향
int[] dir = dirMap.get(st.nextToken().charAt(0));
// 이동 거리
int amount = Integer.parseInt(st.nextToken());
// 해당 이동이 가능한지 확인
if (isOk(park, now, dir, amount)) {
// 가능하면 해당 위치로 이동
now.move(dir[0] * amount, dir[1] * amount);
}
}
return now.toArray();
}
public static boolean isOk(String[] map, Pos pos, int[] dir, int amount) {
int tempRow = pos.row;
int tempCol = pos.col;
// 이동 거리 만큼 검사
for(int i = 0; i < amount; i++) {
tempRow += dir[0];
tempCol += dir[1];
// 이동 가능한지 확인
if (!isMove(map, tempRow, tempCol)) {
return false;
}
// 장애물이 있는지 확인
if (map[tempRow].charAt(tempCol) == 'X') {
return false;
}
}
return true;
}
// 이동 가능한지 확인하는 메소드
public static boolean isMove(String[] map, int r, int c) {
return (0 <= r && r < map.length) && (0 <= c && c < map[0].length());
}
}
처음에 이동 검사를 하나씩 이동하면서 검사해야 하는데 한 번에 이동해서 검사하려고 해서 틀렸었습니다. 그래서 그 부분을 수정하여 해결했습니다.
'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [백준/Java] 35368번 Breakout (0) | 2026.03.19 |
|---|---|
| [프로그래머스/Java] 신고 결과 받기 (0) | 2026.03.19 |
| [프로그래머스/Java] 바탕화면 정리 (0) | 2026.03.18 |
| [백준/Java] 35261번 피갤컵 들어왔으면 이 글부터 봐라 (0) | 2026.03.18 |
| [프로그래머스/Java] [카카오 인턴] 키패드 누르기 (0) | 2026.03.18 |