보라코딩
프로그래머스 자바 :: 공원산책 본문
고민하다가 다른 풀이 보고 푼 문제
신선했던 점은
일단 x, y값을 주고 나서
이후 조건을 따지고
조건에 맞는 변수를 반환하기...!
Map으로 푸는 방법으로도 풀고 싶다!
import java.util.*;
class Solution {
public int[] solution(String[] park, String[] routes) {
// 스타트 지점 찾기
int start_x = -1;
int start_y = -1;
char[][] arr = new char[park.length][park[0].length()];
// 현재 위치
for (int i = 0; i < park.length; i ++) {
arr[i] = park[i].toCharArray();
if (park[i].contains("S")) {
start_y = i;
start_x = park[i].indexOf("S");
}
}
//
for (String route : routes) {
String way = route.split(" ")[0];
int length = Integer.parseInt(route.split(" ")[1]);
int x = start_x;
int y = start_y;
// 조건 신경쓰지 말고 일단 좌표 계산
for ( int i = 0; i < length; i++){
if (way.equals("E")){
x++;
}
if (way.equals("W")){
x--;
}
if (way.equals("S")){
y++;
}
if (way.equals("N")){
y--;
}
// 조건에 맞는 경우에만 start_x, start_y에 넣어서 이걸 반환
if (x >=0 && y >=0 && y < arr.length && x < arr[0].length){
if(arr[y][x] == 'X'){
break;
}
if (i == length - 1) {
start_x = x;
start_y = y;
}
}
}
}
int[] answer = {start_y, start_x};
return answer;
}
}
다른사람 풀이
import java.util.*;
class Solution {
public int[] solution(String[] park, String[] routes) {
int start_x = -1;
int start_y = -1;
char[][] map = new char[park.length][park[0].length()];
// 현재 위치
for(int i = 0; i< map.length; i++){
for(int j = 0; j< map[0].length; j++){
map[i][j] = park[i].charAt(j);
if(map[i][j] == 'S'){
start_x = j;
start_y = i;
}
}
}
HashMap<String, int[]> hash = new HashMap<>();
hash.put("E", new int[]{0, 1});
hash.put("S", new int[]{1, 0});
hash.put("N", new int[]{-1, 0});
hash.put("W", new int[]{0, -1});
loop:
for(int i=0; i<routes.length; i++){
String[] cur = routes[i].split(" ");
int direction[] = hash.get(cur[0]);
int ny = start_y;
int nx = start_x;
for(int j=0; j<Integer.parseInt(cur[1]); j++){
ny += direction[0];
nx += direction[1];
if(ny < 0 || ny >= map.length || nx <0 || nx >= map[0].length || map[ny][nx] == 'X')
continue loop;
}
start_x = nx;
start_y = ny;
}
return new int[] {start_y, start_x};
}
}
'프로그래머스 (java)' 카테고리의 다른 글
프로그래머스 자바 :: 게임 맵 최단거리 (BFS) (0) | 2024.06.20 |
---|---|
프로그래머스 자바 :: 둘만의 암호 (0) | 2024.06.14 |
프로그래머스 자바 :: 신고 결과 받기 (0) | 2024.06.06 |
프로그래머스 자바 :: 개인정보 수집 유효기간 (0) | 2024.05.26 |
프로그래머스 자바 :: 추억점 (0) | 2024.05.25 |