[JS] 프로그래머스 코딩테스트 - 방문길이

권이온·2025년 8월 17일

📚 문제

방문 길이

📣 풀이

  • 시도한 풀이
    function solution(dirs) {
        let map = [...new Array(11)].fill('').map(() => new Array(11).fill(''));
        let answer = 0;
        
        // 시작 위치는 [5][5]. 
        const current = [5, 5];
        
        for (let i = 0; i < dirs.length; i++) {
            // 범위 넘어가면 무시
            if (dirs[i] === 'U' && current[1] === 10) continue;
            else if (dirs[i] === 'D' && current[1] === 0) continue;
            else if (dirs[i] === 'L' && current[0] === 0) continue;
            else if (dirs[i] === 'R' && current[0] === 10) continue;
            // 이동 후 중복체크
            else {
                if (dirs[i] === 'U') {
                    if (-1 === map[current[0]][current[1]].indexOf('U') 
                        && -1 === map[current[0]][current[1] + 1].indexOf('D')) {
                        answer++;
                    }
                    map[current[0]][current[1]] += ('U');
                    current[1]++;
                }
                else if (dirs[i] === 'D') {
                    if (-1 === map[current[0]][current[1]].indexOf('D')
                       && -1 === map[current[0]][current[1] - 1].indexOf('U')) {
                        answer++;
                    }
                    map[current[0]][current[1]] += ('D');
                    current[1]--;
                }
                else if (dirs[i] === 'L') {
                    if (-1 === map[current[0]][current[1]].indexOf('L')
                       && -1 === map[current[0] - 1][current[1]].indexOf('R')) {
                        answer++;
                    }
                    map[current[0]][current[1]] += 'L';
                    current[0]--;
                }
                else { // dirs[i] === 'R'
                    if (-1 === map[current[0]][current[1]].indexOf('R')
                       && -1 === map[current[0] + 1][current[1]].indexOf('L')) {
                        answer++;
                    }
                    map[current[0]][current[1]] += 'R';
                    current[0]++;
                }
            }
        }
        
        return answer;
    }

💫코드 리뷰 & 반성

[어려웠던 점]
중복 체크하기

[새롭게 알게된 점]
중복 체크할 때 문자열도 배열처럼 index로 접근 가능하니까 하면서 접근했는데

배열에서만 findIndex()와 find()를 쓸 수 있고
문자열에서는 indexOf()를 써야 한다.

참고

코딩 테스트 합격자 되기 자바스크립트 - 이선협, 박경록 저

profile
인생은 아름다워

0개의 댓글