728x90
https://school.programmers.co.kr/learn/courses/30/lessons/172928
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
1. Java
import java.util.*;
class Solution {
public int[] solution(String[] park, String[] routes) {
int[] point = new int[2];
int width = park.length;
int height = park[0].length();
boolean[][] roads = new boolean[width][height];
loop:
for ( int x = 0; x < width; ++x ) {
for ( int y = 0; y < height; ++y ) {
char road = park[x].charAt(y);
if ( road == 'S' ) {
point = new int[]{x, y};
roads[x][y] = true;
} else if ( road == 'O' ) {
roads[x][y] = true;
}
}
}
int[] dx = {0, 1, -1, 0}, dy = {1, 0, 0, -1};
Map<String,Integer> direction_info = new HashMap<>() {
{
put("E",0);
put("S",1);
put("N",2);
put("W",3);
}
};
/* Map<String,Integer> direction_info = new HashMap<>();
direction_info.put("E",0);
direction_info.put("S",1);
direction_info.put("N",2);
direction_info.put("W",3); */
for ( String route : routes ) {
String[] r = route.split(" ");
Integer idx = direction_info.get(r[0]);
Integer degree = Integer.parseInt(r[1]);
boolean able = true;
int nx = point[0];
int ny = point[1];
for ( int i = 0; i < degree; ++i ) {
nx += dx[idx];
ny += dy[idx];
if ( nx < 0 || nx >= width
|| ny < 0 || ny >= height
|| !roads[nx][ny] ) {
able = false;
break;
}
}
if ( able ) {
point = new int[]{nx, ny};
}
}
return point;
}
}
2. Python
def solution(park, routes):
point = []
width = len(park)
height = len(park[0])
roads = [[False for col in range(height)] for row in range(width)] #[[]]
for x in range(width) :
for y in range(height) :
p = park[x][y]
if p == 'S' :
point = [x, y]
roads[x][y] = True
elif p == 'O' :
roads[x][y] = True
dx = [0, 1, -1, 0]
dy = [1, 0, 0, -1]
direction_info = {"E":0, "S":1, "N":2, "W":3}
for route in routes :
r = route.split(" ")
idx = direction_info[r[0]]
degree = int(r[1])
# able = True
nx = point[0]
ny = point[1]
for i in range(degree) :
nx += dx[idx]
ny += dy[idx]
if nx < 0 or nx >= width
or ny < 0 or ny >= height
or roads[nx][ny] == False :
# able = False
break
# if able == True :
else :
point = [nx, ny]
return point
반응형
'코딩 문제 풀기 ( Algorithm problem solving ) > 프로그래머스 ( Programmers )' 카테고리의 다른 글
[프로그래머스(Programmers)][Java,Python] (Lv1) 붕대 감기 (PCCP 기출문제 1번) (0) | 2025.03.25 |
---|---|
[프로그래머스(Programmers)][Java,Python] (Lv1) 유연근무제 (0) | 2025.03.25 |
[프로그래머스(Programmers)][Java,Python] (Lv1) 달리기 경주 (0) | 2025.03.24 |
[프로그래머스(Programmers)][Java,Python] (Lv1) 개인정보 수집 유효기간 (2023 KAKAO BLIND RECRUITMENT) (0) | 2025.03.24 |
[프로그래머스(Programmers)][Java,Python] (Lv1) 바탕화면 정리 (0) | 2025.03.21 |