하나의 출발점에서 모든 정점까지의 최단 경로를 찾는 그래프 탐색 알고리즘.
음의 가중치를 가지지 않는 그래프에서 최단 경로를 찾는데 사용한다.
동작은 다음과 같다.
매 단계에서 현재까지의 최단 경로를 선택하기에 최적의 결과를 보장한다.
function Dijkstra(Graph, source):
distance[0:vertices] = inf 값
visited[0:vertices] = false
distance[source] = 0
for i from 1 to |v|-1:
current = min(distance[not_visited])
visited[current] = true
for neighbor of current:
if(distance[current] + neighbor_weight < distance[neighbor])
distance[neighbor] = distance[current] + neighbor_weight
return distance
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#define INF INT_MAX
using namespace std;
struct Edge{
int dest;
int weight;
};
// 다익스트라 알고리즘
void Dijkstra(vector<vector<Edge>>& graph, int source){
int numVertices = graph.size();
vector<int> distances(numVertices, INF);
vector<bool> visited(numVertices, false);
// 출발점의 거리를 0으로
distances[source] = 0;
// 우선순위 큐를 사용, 최단 거리 작은 정점 선택
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> pq;
pq.push(make_pair(0, source));
while(!pq.empty()){
int current = pq.top().second;
pq.pop();
// 이미 방문한 정점은 건너뜀
if(visited[current])continue;
visited[current] = true;
// 현재 정점과 연결된 모든 인접 정점에 대해 최단 거리 갱신
for(const Edge& edge : graph[current]){
int neighbor = edge.dest;
int weight = edge.weight;
if(distances[current]!=INF && distances[current] + weight < distances[neighbor]){
distances[neighbor] = distances[current] + weight;
pq.push(make_pair(distances[neighbor], neighbor));
}
}
}
// 결과 출력
cout << "Vertex\tDistance from Source\n";
for(int i=0;i<numVertices;++i){
cout << i << "\t" << distances[i] << "\n";
}
}
int main()
{
int numVertices = 6;
vector<vector<Edge>> graph(numVertices);
// 그래프 초기화
graph[0].push_back({1, 2});
graph[0].push_back({2, 5});
graph[1].push_back({2, 2});
graph[1].push_back({3, 3});
graph[1].push_back({4, 1});
graph[2].push_back({3, 1});
graph[2].push_back({4, 2});
graph[3].push_back({4, 4});
graph[3].push_back({5, 3});
graph[4].push_back({5, 5});
int source = 0;
Dijkstra(graph, source);
return 0;
}