[백준 15686번] 구현 - 치킨 배달

김민지·2023년 11월 5일
0

냅다 시작 백준

목록 보기
105/118

✨ 문제 ✨


✨ 정답 ✨

const { notDeepEqual } = require("assert");
const { count } = require("console");
const fs = require("fs");
const { nextTick } = require("process");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./예제.txt";
let input = fs.readFileSync(filePath).toString().trim().split('\n');


// const fs = require('fs'); 
// let input = fs.readFileSync("/dev/stdin").toString().trim().split('\n');

const [N, M]=input.shift().split(' ').map((el)=>+el)

let array=[];
for (let i=0;i<N;i++){
    array.push(input[i].split(' ').map((el)=>+el))
}

// 치킨집 위치
let chicken=[]
// 집 위치
let house=[]

for (let i=0;i<N;i++){
    for (let j=0;j<array[0].length;j++){
        if (array[i][j]===1){
            house.push([i,j]);
        }else if (array[i][j]===2){
            chicken.push([i,j])
        }
    }
}
// 치킨 거리 계산
const chickenDistance=(house, chicken)=>{
    return Math.abs(house[0]-chicken[0])+Math.abs(house[1]-chicken[1]);
}

// 치킨집 중 M개를 뽑아야 함.
const combination=(array, selectM)=>{
    let combinationArray2=[];
    if (selectM===1){
        return array.map((el)=>[el])
    }
    array.forEach((current, index, calledArray)=>{
        let rest=calledArray.slice(index+1);
        let combinationResult=combination(rest,selectM-1);
        let attached=combinationResult.map((el)=>[current,...el]);
        combinationArray2.push(...attached)
    })
    return combinationArray2;
}


let length = Array.from({length:chicken.length}, (_,i) => i);
let combintationArray = combination(length, M);


let rArr = [];
combintationArray.forEach(el => {
  let total = 0;
  for(let [a, b] of house){
    let min = 99999999999;
    el.forEach(el2 => {
      let val = Math.abs(chicken[el2][0] - a) + Math.abs(chicken[el2][1] - b);
      if(min > val) min = val; 
    })
    total += min;
  }
  rArr.push(total);
})

console.log(Math.min(...rArr));

🧵 참고한 정답지 🧵

💡💡 기억해야 할 점 💡💡

profile
이건 대체 어떻게 만든 거지?

0개의 댓글