https://school.programmers.co.kr/learn/courses/30/lessons/132266
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
접근 방법
- 임의의 노드에서 도착지까지의 최단거리를 구하면되므로 BFS를 떠올렸다.
- 도착지를 기준으로 n개의 노드를 distMap에 기록하며 거리를 계산하고 출력했다.
코드
import java.util.*;
class Solution {
public int[] solution(int n, int[][] roads, int[] sources, int destination) {
List<List<Integer>> graph = new ArrayList<>();
for(int i = 0 ; i <= n ; i++)graph.add(new ArrayList<>());
for(int[] r: roads){
int s = r[0];
int e = r[1];
graph.get(s).add(e);
graph.get(e).add(s);
}
int[] distMap = new int[n+1];
boolean[] vis = new boolean[n+1];
Queue<int[]> q = new LinkedList<>();
q.offer(new int[]{destination,0});
vis[destination] = true;
while(!q.isEmpty()){
int[] cur = q.poll();
distMap[cur[0]] = cur[1];
for(int next: graph.get(cur[0])){
if(vis[next]) continue;
q.offer(new int[]{next,cur[1]+1});
vis[next] = true;
}
}
int[] answer = new int[sources.length];
for(int i = 0 ; i< sources.length ; i++){
int dist = distMap[sources[i]];
answer[i] = dist == 0 && sources[i] != destination? -1: dist;
}
return answer;
}
}
'Algorithm' 카테고리의 다른 글
[프로그래머스] LV 3 파괴되지 않은 건물 (1) | 2024.11.29 |
---|---|
[프로그래머스] LV 3 경주로 건설 (0) | 2024.11.21 |
[프로그래머스] LV 3 가장 긴 팰린드롬 (0) | 2024.11.17 |
[프로그래머스] LV 2 하노이 탑 (1) | 2024.11.16 |
[프로그래머스] LV 3 정수 삼각형 (0) | 2024.11.11 |