728x90
반응형
목차
문제
https://school.programmers.co.kr/learn/courses/30/lessons/132266
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
문제 구현 방향
처음에 bfs를 생각했었는데 각 시작점에 대해 bfs를 돌릴 경우 시간 복잡도가 날 것 같아 고민했던 문제이다.
목적지를 기준으로 모든 경로를 순회하고 시작점의 거리를 답에 추가해주면 되는 문제였다.
코드 구현
function solution(n, roads, sources, destination) {
var answer = [];
let board = Array.from({length: 100001}, ()=> []);
for(let r of roads){
let [str, end] = r;
board[str].push(end);
board[end].push(str);
}
let dp = Array(100001).fill(Infinity);
let queue = [destination];
dp[destination] =0;
while(queue.length){
let sft = queue.shift();
for(let r of board[sft]){
if(dp[r] === Infinity){
dp[r] = dp[sft] + 1;
queue.push(r);
}
}
}
for(let src of sources){
answer.push(isFinite(dp[src]) ? dp[src] : -1);
}
return answer;
}반응형
'PS > 프로그래머스' 카테고리의 다른 글
| [프로그래머스][union find] 셀 병합 (0) | 2025.09.19 |
|---|---|
| [프로그래머스][백트래킹] 양궁대회 (0) | 2025.09.18 |
| [프로그래머스][슬라이딩 윈도우] 두 큐 합 같게 만들기 (0) | 2025.09.15 |
| [프로그래머스][dp] 숫자 변환하기 (0) | 2025.09.11 |
| [프로그래머스][bfs] 미로 탈출 명령어 (0) | 2025.09.09 |