코테/프로그래머스

[프로그래머스/Level3] 부대 복귀 (JAVA)

imname1am 2024. 6. 8. 18:37
반응형

📖 문제

 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

💡  풀이 방식

• BFS

필요 자료구조
- 인접 리스트
- 1차원 최단 거리 배열 (destination으로부터의 최단 거리를 나타냄)

 

1. 인접 리스트 그래프 graph에 길 정보를 저장한다.

2. 최단 거리 배열을 모두 최댓값으로 저장한다.

3. 시작점 destination부터 BFS를 진행하며 최단 거리 배열을 채운다.

for(int next : graph[now]) {                
    if(dist[now] + 1 < dist[next]) {    // 최단 거리 갱신
        dist[next] = dist[now] + 1;
        q.add(next);
    }
}

 

 

 

🔺 코드

1. List<List<Integer>>를 활용한 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
 
class Solution {
    static final int INF = Integer.MAX_VALUE;
    static List<List<Integer>> graph;
    static int[] dist;    // 최단 거리 배열
    
    public int[] solution(int n, int[][] roads, int[] sources, int destination) {
        graph = new ArrayList<>();
        for(int i = 0 ; i <= n ; i++) {
            graph.add(new ArrayList<>());
        }
                
        for(int[] r : roads) {            
            graph.get(r[0]).add(r[1]);
            graph.get(r[1]).add(r[0]);
        }
        
        dist = new int[n+1];
        Arrays.fill(dist, INF);
       dijkstra(n, destination);
        
        int[] answer = new int[sources.length];
        for(int i = 0 ; i < sources.length ; i++) {
            int v = dist[sources[i]];
            answer[i] = (v == INF) ? -1 : v;
        }
        
        return answer;
    }
    
    private static void dijkstra(int n, int destination) {
        Queue<Integer> q = new LinkedList<>();
        q.add(destination);
 
        dist[destination] = 0;    // 시작점        
        
        while(!q.isEmpty()) {
            int now = q.poll();
            
            for(int i = 0 ; i < graph.get(now).size() ; i++) {
                int next = graph.get(now).get(i);
                
                // 최단 거리 갱신
                if(dist[now] + 1 < dist[next]) {
                    dist[next] = dist[now] + 1;
                    q.add(next);
                }
            }
        }     
    }
}
cs

 

 

 

 

2. List<Integer>[]>를 활용한 풀이 ✅

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;
 
class Solution {
    static final int INF = Integer.MAX_VALUE;
    static List<Integer>[] graph;
    static int[] dist; // 최단 거리 배열
    
    public int[] solution(int n, int[][] roads, int[] sources, int destination) {
        graph = new ArrayList[n+1];
        for(int i = 0 ; i <= n ; i++) {
            graph[i] = new ArrayList<>();
        }
                
        for(int[] r : roads) {            
            graph[r[0]].add(r[1]);
            graph[r[1]].add(r[0]);
        }
        
        dist = new int[n+1];
        Arrays.fill(dist, INF);
        
       dijkstra(n, destination);
        
        int[] answer = new int[sources.length];
        for(int i = 0 ; i < sources.length ; i++) {
            int v = dist[sources[i]];
            answer[i] = (v == INF) ? -1 : v;
        }
        
        return answer;
    }
    
    private static void dijkstra(int n, int destination) {
        Queue<Integer> q = new LinkedList<>();
        q.add(destination);
        
        dist[destination] = 0;    // 시작점   
        
        while(!q.isEmpty()) {
            int now = q.poll();
            
            for(int next : graph[now]) {                
                if(dist[now] + 1 < dist[next]) {    // 최단 거리 갱신
                    dist[next] = dist[now] + 1;
                    q.add(next);
                }
            }
        }     
    }
}
cs

 

 

 

➕ 다른 풀이 방식

1) 다익스트라 (우선순위 큐 O)를 사용한 풀이 1

 

[프로그래머스] 부대복귀 (Java)

막 어려운 문제라기보다는, 생각의 전환을 잘 하고 싶어서 글을 적게 된 문제이다. 문제 https://school.programmers.co.kr/learn/courses/30/lessons/132266?language=java 프로그래머스 코드 중심의 개발자 채용. 스택

codingwell.tistory.com

 

 

2) 다익스트라를 활용한 풀이 2

 

 

[프로그래머스] 부대복귀

프로그래머스 : 부대복귀 (Java) 문제 링크 확인 풀이 최단 거리를 구하는 문제이다. 문제가 어려운 것 같지만 차근차근 읽어보면 생각보다 쉽게 문제를 풀 수 있다. 문제에서 주어진 조건을 정리

yoo-dev.tistory.com


💦 어려웠던 점

-처음에 플로이드-와샬 풀었다가 O(N^3)의 시간 복잡도로 인해 시간 초과, 메모리 초과 이슈 발생.. (아무래도 10만을 세제곱하면 오바니까..)

 

 

1회독 2회독 3회독 4회독 5회독
V        

(참고)

✔ 풀이 참고

 

[pro] 프로그래머스 level3 132266 부대복귀 (Java) - 다익스트라

[문제] https://school.programmers.co.kr/learn/courses/30/lessons/132266 프로그래머스 코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이

stritegdc.tistory.com

 

✔ 문제 시간 복잡도 관련 참

 

프로그래머스 - 부대복귀(Java)

다익스트라(dijkstra) 문제입니다. 연결 정보가 주어지고, 여러 출발지에서 하나의 목적지 까지로 가는 가중치를 구하는 문제입니다. 무방향 그래프이기 때문에 이를 반대로 생각하면, 하나의 목

ksb-dev.tistory.com

 

반응형