문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr

1 번째 시도
구현 문제여서 아이디어는 설명 안하겠다.
- isWalk: 갈 수 있는 길인지 확인하는 함수
- separate: 방향, 거리를 계산해 {x,y}로 반환하는 함수
import java.util.*;
class Solution {
public int[] solution(String[] park, String[] routes) {
int xLength = park[0].length();
int yLength = park.length;
int[] startInd = new int[2];
startInd[0] = -1;
//시작점 S 찾기
for(int i =0 ; i < park.length; i++) {
for(int j = 0; j < park[i].length(); j++) {
if(park[i].charAt(j) == 'S') {
startInd[0] = j;
startInd[1] = i;
break;
}
}
if(startInd[0] != -1)
break;
}
int curX = startInd[0];
int curY = startInd[1];
for(int i = 0; i < routes.length; i++) {
String[] split = routes[i].split(" ");
String dir = split[0];
int dis = Integer.parseInt(split[1]);
int[] rout = separate(routes[i]);
if(isWalk(park, curX, curY, dis, dir)){
curX = curX + rout[0];
curY = curY + rout[1];
}
}
return new int[]{curY,curX};
}
public boolean isWalk(String[] park, int curX, int curY, int distance, String dir) {
int deltaX = 0, deltaY = 0;
if (dir.equals("E")) deltaX = 1;
else if (dir.equals("W")) deltaX = -1;
else if (dir.equals("S")) deltaY = 1;
else if (dir.equals("N")) deltaY = -1;
for (int step = 1; step <= distance; step++) {
int newX = curX + deltaX * step;
int newY = curY + deltaY * step;
// Check bounds
if (newX < 0 || newX >= park[0].length() || newY < 0 || newY >= park.length) {
return false;
}
// Check for obstacles
if (park[newY].charAt(newX) == 'X') {
return false;
}
}
return true;
}
public int[] separate(String route) {
String[] split = route.split(" ");
String dir = split[0];
int dis = Integer.parseInt(split[1]);
if(dir.equals("E")){
return new int[]{1*dis,0};
}
else if( dir.equals("W")) {
return new int[]{-1*dis,0};
}
else if( dir.equals("S")) {
return new int[]{0,1*dis};
}
else {
return new int[]{0,-1*dis};
}
}
}

'알고리즘 > 구현' 카테고리의 다른 글
[백준 2504] 괄호의 값 / 자바 / 구현(괄호) (0) | 2024.08.02 |
---|---|
[백준 17144] 미세먼지 안녕! / 자바 / 구현 (0) | 2024.08.02 |
[백준 20058] 마법사 상어와 파이어스톰 / 자바 / 구현 + bfs 조금 *** (0) | 2024.07.29 |
[백준 13458] 시험감독 / 자바 /그리드 (0) | 2024.07.03 |
[백준 3190] 뱀 / 자바 / 구현 (0) | 2024.07.03 |