본문 바로가기
알고리즘

[프로그래머스] Lv 2. 거리두기 확인하기 - Javascript 풀이

by daami 2025. 3. 1.

문제 링크 

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

구현

function solution(places) {
    //각 대기실마다 거리두기를 지켰는지 확인하는 함수
    const checkRule = (place) => {
        //문자열을 배열로 변환 
        const placeArr = place.map(row => [...row]);
        
        //P 좌표들
        const poses = [];
        
        //P를 찾는다 => 좌표 추출 => 거리 계산
        for(let i=0;i<5;i++){
            for(let j=0;j<5;j++){
                if(placeArr[i][j] === 'P'){
                    poses.push([i,j]);
                }
            }
        }
        
        //모든 항목에 대해 거리 계산
        for(let i=0; i<poses.length;i++){
            for(let j=i+1;j<poses.length;j++){
                const [x1, y1] = poses[i];
                const [x2, y2] = poses[j];
                const distance = Math.abs(x1-x2) + Math.abs(y1-y2);
                
                //거리가 2이하면, 사이에 있는 항목 확인
                if(distance<=2){
                    let isSafe = false;
                    
                    // 1. 수직
                    if(x1===x2 && Math.abs(y1-y2)===2){
                        if(placeArr[x1][(y1+y2)/2]==='X'){
                            isSafe = true;
                        }
                    }
                    //2. 수평
                    if(y1===y2 && Math.abs(x1-x2)===2){
                        if(placeArr[(x1+x2)/2][y1] === 'X'){
                            isSafe = true;
                        }
                    }
                    
                    //3. 대각선
                    if(Math.abs(x1-x2) === 1 && Math.abs(y1-y2) === 1){
                        if(placeArr[x1][y2]==='X' && placeArr[x2][y1]==='X'){
                            isSafe = true;
                        }
                    }
                    
                    if(!isSafe){
                        return 0;
                    }
                }
            }
        }
        return 1;
    };
    
        return places.map(checkRule);
    
}

 

처음에는 구조분해 할당을 통해

const [place1, place2, place3, place4, place5] = places;

이렇게 두고 각 항목마다 checkRule 함수를 적용했었다.

 

map을 활용하면 배열 안의 주어진 모든 요소에 함수를 적용해서 새로운 배열을 만들 수 있다.

 

 

* 2차원 배열에서 특정 문자열의 위치 정보 찾기 => 2중 순회 활용

if(arr[i][j] === 'X') return [i,j];