문제: https://school.programmers.co.kr/learn/courses/30/lessons/132266
(풀이방식1)
인접 리스트를 활용한 BFS로 풀이
→ 양쪽으로 이동이 가능해야하기때문에 map을 구성하되 양쪽 노드 모두 추가해주기
sources를 돌며 source가 root가 됨
→ source 별로 queue while문 별도 진행
→ 꺼낸 값이 destination과 같을 경우 cnt return
→ 없을 경우 -1
answer 배열 return
⇒ 시간초과
(풀이방식2)
import java.util.*;
class Solution {
public int[] solution(int n, int[][] roads, int[] sources, int destination) {
Map<Integer, List<Integer>> graph = new HashMap<>();
Map<Integer, Boolean> visited = new HashMap<>();
// boolean[] visited = new boolean[n];
int[] answer = new int[sources.length];
int answerIdx = 0;
// 인접리스트 graph (key: 도착지, value: 출발지)
for(int[] road : roads){
int start = road[0];
int end = road[1];
// 출발지 기준 추가
if(!graph.containsKey(start)){
graph.put(start, new ArrayList<>(Arrays.asList(end)));
}else{
graph.get(start).add(end);
}
// 도착지 기준 추가
if(!graph.containsKey(end)){
graph.put(end, new ArrayList<>(Arrays.asList(start)));
}else{
graph.get(end).add(start);
}
}
for(int source : sources){
// 도착지일 경우 0
if(source == destination){
answer[answerIdx++] = 0;
continue;
}
// 초기 세팅
Queue<int[]> q = new ArrayDeque<>();
visited.clear();
visited.put(source, true);
q.add(new int[]{source, 1});
while (!q.isEmpty()) {
int[] cur = q.poll();
int curV = cur[0];
int curDist = cur[1];
if(!graph.containsKey(curV)){ // containsKey가 안될 경우 X
answer[answerIdx++] = -1;
}else{
for(int nextV : graph.get(curV)){
if(nextV == destination){
answer[answerIdx++] = curDist;
q.clear();
break;
}else{
if(!visited.containsKey(nextV)){
visited.put(nextV, true);
q.add(new int[]{nextV, curDist+1});
}
}
}
}
}
}
return answer;
}
}
import java.util.*;
class Solution {
public int[] solution(int n, int[][] roads, int[] sources, int destination) {
Map<Integer, List<Integer>> graph = new HashMap<>();
boolean[] visited = new boolean[n+1];
int[] answerList = new int[n + 1];
Arrays.fill(visited, false);
Arrays.fill(answerList, -1);
// 인접리스트 graph (key: 도착지, value: 출발지)
for(int[] road : roads){
int start = road[0];
int end = road[1];
// 출발지 기준 추가
if(!graph.containsKey(start)){
graph.put(start, new ArrayList<>(Arrays.asList(end)));
}else{
graph.get(start).add(end);
}
// 도착지 기준 추가
if(!graph.containsKey(end)){
graph.put(end, new ArrayList<>(Arrays.asList(start)));
}else{
graph.get(end).add(start);
}
}
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[]{destination, 0});
visited[destination] = true;
answerList[destination] = 0;
while(!q.isEmpty()){
int[] cur = q.poll();
int curV = cur[0];
int curDist = cur[1];
for(int nextV : graph.get(curV)){
if(!visited[nextV]){
q.add(new int[]{nextV, curDist+1});
visited[nextV] = true;
answerList[nextV] = curDist+1;
}
}
}
int[] answer = new int[sources.length];
int answerIdx = 0;
for(int source: sources){
answer[answerIdx++] = answerList[source];
}
return answer;
}
}
BFS에 대해서 더 자세하게 공부해야할거같네요 ㅜ..