티스토리 뷰

Algorithm

[c++] 다익스트라 알고리즘

angieveloper 2022. 5. 20. 11:27

 

#include <iostream>
#include <vector>
#include <queue>
#include <utility>

using namespace std;

int number = 6;
int INF = 1000000000;

vector<pair<int, int>> a[7];
int d[7];

void init()
{
    for (int i = 1; i <= number; i++)
        d[i] = INF;

    a[1].push_back({2, 2});
    a[1].push_back({3, 5});
    a[1].push_back({4, 1});

    a[2].push_back({1, 2});
    a[2].push_back({3, 3});
    a[2].push_back({4, 2});

    a[3].push_back({1, 5});
    a[3].push_back({2, 3});
    a[3].push_back({4, 3});
    a[3].push_back({5, 1});
    a[3].push_back({6, 5});

    a[4].push_back({1, 1});
    a[4].push_back({2, 2});
    a[4].push_back({3, 3});
    a[4].push_back({5, 1});

    a[5].push_back({3, 1});
    a[5].push_back({4, 1});
    a[5].push_back({6, 2});

    a[6].push_back({3, 5});
    a[6].push_back({5, 2});
}

struct compare
{
    bool operator()(pair<int, int> a, pair<int, int> b)
    {
        return a.second < b.second;
    }
};

void dijkstra(int start)
{
    d[start] = 0;

    priority_queue<pair<int, int>, vector<pair<int, int>>, compare> pq;
    pq.push({start, 0});

    while (!pq.empty())
    {
        int current = pq.top().first;
        int distance = pq.top().second;
        pq.pop();

        if (d[current] < distance)
            continue;
        for (auto node : a[current])
        {
            int next = node.first;
            int nextDistance = distance + node.second;
            if (d[next] > nextDistance)
            {
                d[next] = nextDistance;
                pq.push({next, nextDistance});
            }
        }
    }
}

void printDistance()
{
    for (int i = 0; i < number; i++)
        printf("%d ", d[i]);
}

int main(void)
{
    init();
    dijkstra(1);
    printDistance();
    return 0;
}

 

코드 참고 : https://blog.naver.com/ndb796/221234424646

 

23. 다익스트라(Dijkstra) 알고리즘

다익스트라(Dijkstra) 알고리즘은 다이나믹 프로그래밍을 활용한 대표적인 최단 경로(Shortest Path) 탐...

blog.naver.com

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함