[프로그래머스] 배달 (Java)

nnm·2020년 5월 5일
0

프로그래머스 배달

문제풀이

다익스트라 알고리즘을 이용해서 최단거리를 구하는 문제였다. 다익스트라는 현재 저장된 거리와 새로 도달가능한 거리를 비교해 최단거리를 갱신해나가는 알고리즘이다.

  • 우선순위 큐를 이용해서 효율을 높인다.
  • 인접리스트 사용

구현코드

import java.util.*;

class Solution {
    class Edge implements Comparable<Edge> {
        int to, weight;
        
        Edge(int to, int weight){
            this.to = to;
            this.weight = weight;
        }
        
        @Override
        public int compareTo(Edge e){
            return this.weight - e.weight;
        }
    }
    
    PriorityQueue<Edge> pq;
    ArrayList<ArrayList<Edge>> adj;
    int[] dist;
    
    public int solution(int N, int[][] road, int K) {
        int answer = 0;
        
        pq = new PriorityQueue<>();
        adj = new ArrayList<>();
        dist = new int[N + 1];
        
        Arrays.fill(dist, Integer.MAX_VALUE);
        for(int i = 0 ; i <= N ; ++i) adj.add(new ArrayList<>());
    
        for(int i = 0 ; i < road.length ; ++i){
            int from = road[i][0];
            int to = road[i][1];
            int weight = road[i][2];
            
            adj.get(from).add(new Edge(to, weight));
            adj.get(to).add(new Edge(from, weight));
        }
        
        dist[1] = 0;
        pq.offer(new Edge(1, 0));
        
        dijkstra();
        
        for(int distance : dist){
            if(distance <= K) answer++;
        }
        
        return answer;
    }
    
    private void dijkstra() {
        while(!pq.isEmpty()){
            Edge e = pq.poll();
            
            for(Edge ne : adj.get(e.to)){
                if(dist[ne.to] > dist[e.to] + ne.weight){
                    dist[ne.to] = dist[e.to] + ne.weight;
                    pq.offer(ne);
                }
            }
        }
    }
}
profile
그냥 개발자

2개의 댓글

comment-user-thumbnail
2020년 10월 26일

덕분에 쉽게 이해했습니다 감사합니다
혹시 프로그래머스 문제에 링크 첨부후에 답안 제출해도 괜찮을까요?

1개의 답글