Greedy Algorithm - Dijkstra Algorithm

Review


Dijkstra's Algorithm


Code

#include <iostream>
#include <vector>
#include <queue>
#include <limits>
 
using namespace std;
 
// (가중치, 노드)값을 나타내는 상수
typedef pair<int, int> pil;
 
void dijkstra(vector<vector<pil> >& graph, int start, vector<int>& distance) {
    // 시작 노드의 거리를 0으로 초기화
    distance[start] = 0;
 
    // min heap을 사용하는 우선순위 큐
    priority_queue<pil, vector<pil>, greater<pil> > pq;
    // 시작 노드의 가중치는 0으로 설정
    pq.push(make_pair(0, start));
 
    while(!pq.empty()) {
        // 현재 선택된 노드
        int curr_node = pq.top().second;
        // 현재 노드까지의 거리(가중치 값으로 초기화)
        int curr_dist = pq.top().first;
        pq.pop();
 
        // 이미 처리한 노드면 건너뛴다.
        if(curr_dist > distance[curr_node]) continue;
 
        // 현재 노드와 연결된 인접 노드를 탐색한다.
        for(int i = 0; i < graph[curr_node].size(); ++i) {
            // 다음 노드
            int next_node = graph[curr_node][i].second;
            // 다음 노드까지의 거리
            int next_dist = curr_dist + graph[curr_node][i].first;
 
            // 다음 노드까지의 거리가 현재 기록된 거리보다 짧다면 갱신 후 큐에 삽입한다.
            if(next_dist < distance[next_node]) {
                distance[next_node] = next_dist;
                pq.push(make_pair(next_dist, next_node));
            }
        }
    }
}
 
int main() {
    int n = 5; // 노드의 개수
    int start_node = 1; // 시작 노드
 
    // 그래프 초기화
    vector<vector<pil> > graph(n + 1); // 인덱스를 1부터 사용하기 위해 크기를 n+1로 설정
    graph[1].push_back(make_pair(7, 2));
    graph[1].push_back(make_pair(4, 3));
    graph[1].push_back(make_pair(6, 4));
    graph[1].push_back(make_pair(1, 5));
    graph[3].push_back(make_pair(2, 2));
    graph[3].push_back(make_pair(5, 4));
    graph[4].push_back(make_pair(3, 2));
    graph[5].push_back(make_pair(1, 4));
 
    // 최단 거리를 저장하는 배열 초기화
    vector<int> distance(n + 1, INT_MAX);
 
    // 다익스트라 알고리즘 호출
    dijkstra(graph, start_node, distance);
 
    // 결과 출력
    for (int i = 1; i <= n; ++i) {
        if (distance[i] == INT_MAX)
            cout << "INF ";
        else
            cout << "1 -> " << i << " : " << distance[i] << endl;
    }
    cout << endl;
 
    return 0;
}

Every-case Time Complexity of Dijkstra Algorithm