문제 및 코드
프로그래머스
- 코딩테스트 연습 > 연습문제 > 공원 산책
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
// 방향 정보
const directionMap = {
'E': ['y', +1],
'W': ['y', -1],
'S': ['x', +1],
'N': ['x', -1],
}
function solution(park, routes) {
// 시작점을 찾는 함수
const findStartPos = (p) => {
const x = p.findIndex(v => v.includes('S'));
const y = [...p[x]].indexOf('S');
return {x , y};
}
let pos = findStartPos(park);
// 이동 시 장애물이나 범위를 벗어나는 경우 기존 위치값을 반환
const checkPossible = (current, dir, dis) => {
const [d, n] = directionMap[dir];
const next = {...current};
for(let i = 0; i < dis; i++){
next[d] += n;
if (
next.x < 0 || next.x >= park.length ||
next.y < 0 || next.y >= park[0].length ||
park[next.x][next.y] === 'X'
) {
return current;
}
}
return next;
}
routes.forEach((v) => {
const [dir, distance] = v.split(' ');
pos = checkPossible({...pos}, dir, parseInt(distance));
});
return [pos.x, pos.y];
}
오답노트
문제 요약
- 공원이 2차원 배열로 주어짐
- 시작점(S)에서 여러 이동 명령(routes)을 수행
- 경계 벗어나거나 장애물(X)을 만나면 이동 취소
1. 런타임 에러
처음 조건문에 park[next.x][next.y] !== 'O' 이라고만 적어서 런타임 에러가 났다.
그래서 범위를 벗어나 undefined가 발생할 경우를 조건문에 추가하여 해결했다.
// Before
if (park[next.x][next.y] !== 'O') {
return current;
}
// After
if (
next.x < 0 || next.x >= park.length ||
next.y < 0 || next.y >= park[0].length ||
park[next.x][next.y] !== 'O'
) {
return current;
}
2. 시작점을 다시 지나가는 경우
시작점(S)을 다시 지나는 경우가 있다는 점을 생각지 못했다. 때문에 10번과 18번에서 계속 실패하였다.
조건에 'O'가 아닌 경우에 시작점(S)도 해당하여 시작점을 지나는 경우의 이동 명령이 취소됨으로 장애물(X)일 경우로 코드를 수정해 해결하였다.
// Before
if (
next.x < 0 || next.x >= park.length ||
next.y < 0 || next.y >= park[0].length ||
park[next.x][next.y] !== 'O'
) {
return current;
}
// After
if (
next.x < 0 || next.x >= park.length ||
next.y < 0 || next.y >= park[0].length ||
park[next.x][next.y] === 'X'
) {
return current;
}'코딩테스트' 카테고리의 다른 글
| 25.07.20 프로그래머스 - 바탕화면 정리 (1) | 2025.07.20 |
|---|---|
| 25.07.12 프로그래머스 - 추억점수 (0) | 2025.07.12 |