-
[ PS ] 공원 산책Algorithm/Problem Solving 2023. 11. 16. 02:02
https://school.programmers.co.kr/learn/courses/30/lessons/172928
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
프로그래머스 LV2 리코쳇 로봇 하위 호환 문제이다.
한 방향으로 쭉 이동하는 코드 포맷은 익히면 좋을 것 같다.
이전에는 시작 지점을 2중 for문으로 탐색했었는데, includes와 indexOf를 사용해봤다.
const solution = (park, routes) => { const H = park.length; const W = park[0].length; const dy = [-1, 1, 0, 0]; const dx = [0, 0, -1, 1]; // 문제에서 제시하는 방향과 dx,dy 매핑 const dir_mapping = { N: 0, S: 1, W: 2, E: 3, }; let [crnt_y, crnt_x] = [0, 0]; // 시작 지점 탐색 for (let i = 0; i < park.length; i++) { if ([...park[i]].includes("S")) { [crnt_y, crnt_x] = [i, [...park[i]].indexOf("S")]; } } for (let route of routes) { let isValid = true; let [temp_y, temp_x] = [crnt_y, crnt_x]; const [dir, n] = route.split(" "); let count = 0; // 한 방향 쭉 이동 while (count < n) { const [next_y, next_x] = [temp_y + dy[dir_mapping[dir]], temp_x + dx[dir_mapping[dir]]]; // 범위 밖 or "X" if (next_y < 0 || next_y >= H || next_x < 0 || next_x >= W || park[next_y][next_x] === "X") { isValid = false; break; } [temp_y, temp_x] = [next_y, next_x]; count += 1; } if (isValid) { [crnt_y, crnt_x] = [temp_y, temp_x]; } } return [crnt_y, crnt_x]; };
리코쳇 로봇에서 한 방향으로 쭉 이동하는 코드 부분을 살펴보면,
while (true) { let [next_y, next_x] = [temp_y + dy[i], temp_x + dx[i]]; // 벽 또는 장애물에 부딪히지 않을 경우 if (next_y >= 0 && next_y < H && next_x >= 0 && next_x < W && board[next_y][next_x] !== "D") { temp_y = next_y; temp_x = next_x; // 벽 또는 장애물에 부딪힐 경우 } else { if (!visited[temp_y][temp_x]) { if (board[temp_y][temp_x] === "G") { return count + 1; } visited[temp_y][temp_x] = true; queue.push([temp_y, temp_x, i, count + 1]); } break; } }
한 방향으로 쭉 이동하는 코드의 포맷을 기억하자.
- 쭉 이동 : while문
- 멈추는 조건 : break
- 다음 칸으로 이동 : [temp_y, temp_x] = [next_y, next_x]
'Algorithm > Problem Solving' 카테고리의 다른 글
[ PS ] 프로그래머스 LV2 리코쳇 로봇 (0) 2023.07.05 [Javascript] 백준 1987 알파벳 (0) 2023.03.09 [Javascript] 프로그래머스 LV2 귤 고르기 (0) 2022.11.24 [Javascript][Python] 프로그래머스 LV2 큰 수 만들기 (0) 2022.11.15 [Python] 프로그래머스LV2 타겟 넘버 (0) 2022.11.01