코딩테스트/그래프
[프로그래머스/JavaScript] 방문 길이 (Level 2)
고코모옹
2021. 6. 12. 15:10
https://programmers.co.kr/learn/courses/30/lessons/49994
코딩테스트 연습 - 방문 길이
programmers.co.kr
1. 문제 설명
- 위 링크 참고
2. 문제 풀이
- 방문한 좌표 목록을 관리하고 방문 여부는 이동전에서 이동후의 간선(edge)으로 판단을 해야함
- 방문한 좌표 목록은 [이동전index, 이동후index]로 관리를 하고 index는 좌측 위부터 0으로 판단
- find 메소드를 사용하여 방문여부 확인
- 방문을 하지 않은 경우 count를 증가시키고 방문한 좌표 목록에 추가
function solution(dirs) {
let count = 0;
const moveObj = {
"U": [0, 1],
"D": [0, -1],
"R": [1, 0],
"L": [-1, 0]
}
let pos = [0,0]; // 현재위치
const visited = []; // 방문한 좌표 목록
for(let i = 0, len = dirs.length; i < len; i++) {
const moveValue = moveObj[dirs[i]];
const move = [pos[0] + moveValue[0], pos[1] + moveValue[1]]; // 이동할 좌표
// 좌표평면의 경계를 넘어가는 경우
if(move[0] > 5 || move[0] < -5 || move[1] > 5 || move[1] < -5) {
continue;
}
const startIndex = (5+pos[0]) + (5-pos[1]) * 11; // 이동전 좌표
const endIndex = (5+move[0]) + (5-move[1]) * 11; // 이동후 좌표
pos = move;
// 방문여부 확인
const isVisited = visited.find((item) => {
if( (item[0] === startIndex && item[1] === endIndex)
|| (item[0] === endIndex && item[1] === startIndex) ) {
return true;
}
})
if( !isVisited ) {
++count;
visited.push([startIndex, endIndex]);
}
}
return count;
}