본문 바로가기
Coding Test/Programmers

[Programmers] (2021 카카오 채용연계형 인턴십) Lv 2. 거리두기 확인하기

by song.ift 2023. 3. 23.

https://school.programmers.co.kr/learn/courses/30/lessons/81302#fnref1

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

function solution(places) {
    return places.reduce((acc, data) => {
        // 굳이 완전 탐색을 써서 모든 경로를 찾아 itv를 비교하는 것보단,
        // itv가 2인 데이터인것들만 추출해서 그 사이 경로에 X가 있는지 체크하는 게 더 효율적이라 판단.

        const peoples = []; // P인 데이터만 담아둘 배열
        data.forEach((el, i) => {
           [...el].forEach((el, j) => {
               if (el === "P") peoples.push([i, j]);
           })
        });

        const between = []; // 간격이 2인 인덱스들만 담아서, 중간에 X가 있는지 체크할 배열
        for (let i = 0; i < peoples.length - 1; ++i) {
            for (let j = i + 1; j < peoples.length; ++j) {
                const itv = Math.abs(peoples[i][0] - peoples[j][0]) + Math.abs(peoples[i][1] - peoples[j][1]);
                if (itv === 1) { // 간격이 1이면 더 검사할 필요없이 거리두기가 안된걸로 판단해서 로직 종료.
                    acc.push(0);
                    return acc;
                } else if (itv === 2) between.push([peoples[i], peoples[j]]);
            }
        }

        for (const [pivot, dest] of between) {
            // pivot을 기준으로 dest 와의 방향을 판단.
            // between에 데이터를 삽입할 때, 왼쪽 상단부터 순차적으로 저장했기 때문에 dest로의 방향은 무조건 +임.

            const line = pivot[0] === dest[0] || pivot[1] === dest[1] ? true : false; // X를 체크해야할 자리가 2개인지, 1개인지 알기위해 같은 line인지 체크
            const [betX, betY] = [pivot[0] + (dest[0] - pivot[0]) / 2, pivot[1] + (dest[1] - pivot[1]) / 2];

            if (line && (data[betX][betY] !== "X")
                || !line && ([data[dest[0]][pivot[1]], data[pivot[0]][dest[1]]].some((o) => o !== "X"))) {
                acc.push(0);
                return acc;
            }
        }

        acc.push(1);
        return acc;
    }, []);
}

GitHub : https://github.com/developeSHG/Algorithm-Baekjoon_Programmers/tree/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/lv2/81302.%E2%80%85%EA%B1%B0%EB%A6%AC%EB%91%90%EA%B8%B0%E2%80%85%ED%99%95%EC%9D%B8%ED%95%98%EA%B8%B0

 

GitHub - developeSHG/Algorithm-Baekjoon_Programmers: 백준 and 프로그래머스 소스코드

백준 and 프로그래머스 소스코드. Contribute to developeSHG/Algorithm-Baekjoon_Programmers development by creating an account on GitHub.

github.com

 

댓글