https://school.programmers.co.kr/learn/courses/30/lessons/49994#
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
function solution(dirs) {
const visited = new Set();
let current = [0, 0];
// U D R L
const dr = [1, -1, 0, 0] // row 방향
const dc = [0, 0, 1, -1] // col 방향
dirs.split('').forEach(dir => {
let nextRow = current[0];
let nextCol = current[1];
if (dir === 'U') {
nextRow += dr[0];
nextCol += dc[0];
} else if (dir === 'D') {
nextRow += dr[1];
nextCol += dc[1];
} else if (dir === 'R') {
nextRow += dr[2];
nextCol += dc[2];
} else {
nextRow += dr[3];
nextCol += dc[3];
}
// 이동 가능하면
if (nextRow >= -5 && nextRow <= 5 && nextCol >= -5 && nextCol <= 5) {
const path1 = `${current[0]},${current[1]} -> ${nextRow},${nextCol}`;
const path2 = `${nextRow},${nextCol} -> ${current[0]},${current[1]}`;
// 양방향 경로를 모두 체크
if (!visited.has(path1) && !visited.has(path2)) {
visited.add(path1);
visited.add(path2);
}
// 좌표 업데이트
current = [nextRow, nextCol];
}
})
return visited.size / 2;
}
왕복 경로를 동일한 경로로 간주해야 된다.
'코딩테스트 > Programmers' 카테고리의 다른 글
표 편집 (JS) (1) | 2025.01.05 |
---|---|
크레인 인형 뽑기 (JS) (0) | 2025.01.05 |
실패율 (JS) (0) | 2025.01.05 |
최소직사각형 (JS) (0) | 2024.06.02 |
소수 찾기 (JS) (0) | 2024.06.02 |