문제 - 부대복귀
import java.util.*;
class Solution {
ArrayList<Integer> lists[];
public int[] solution(int n, int[][] roads, int[] sources, int destination) {
int[] answer = new int[sources.length];
//이동할 수 있는 길 연결
lists = new ArrayList[n+1];
for(int i=0;i<=n;i++)
{
lists[i] = new ArrayList<>();
}
for(int i =0;i<roads.length;i++)
{
lists[roads[i][0]].add(roads[i][1]);
lists[roads[i][1]].add(roads[i][0]);
}
int cost[] = new int[n+1];//해당 경로에 필요한 비용 계산
Arrays.fill(cost,-1); //경로가 없는 경우 -1로 설정
bfs(destination,cost);
for(int i = 0;i< sources.length;i++ )
{
answer[i] = cost[sources[i]];
}
return answer;
}
public void bfs(int start,int []cost)
{
Queue<Integer> q = new LinkedList<>();
q.offer(start);
cost[start] = 0;
while(!q.isEmpty())
{
int cnt = q.poll();
int len = lists[cnt].size();
for(int i=0;i<len;i++ )
{
int next = lists[cnt].get(i);
if(cost[next] == -1)
{
q.offer(next);
cost[next] = cost[cnt] + 1;
}
}
}
}
}