diff --git a/_posts/2025-02-16-dijkstra-priority-queue.md b/_posts/2025-02-16-dijkstra-priority-queue.md index 65562399..5056f606 100644 --- a/_posts/2025-02-16-dijkstra-priority-queue.md +++ b/_posts/2025-02-16-dijkstra-priority-queue.md @@ -79,7 +79,7 @@ C++을 이용하여 예시 코드를 작성하였다. 아래 링크에서 전체 ```c++ struct Node { - int vertex; // vertex number(id) + int id; // vertex number(id) int cost; // cost to reach the vertex bool operator>(const Node& other) const { // for min-heap return this->cost > other.cost; @@ -92,37 +92,34 @@ struct Node { ```c++ vector dijkstra(int start, int nVertex, vector>& graph) { priority_queue, greater> pq; - vector costs(nVertex, numeric_limits::max()); + vector costs(nVertex, INF); costs[start] = 0; pq.push({start, 0}); while (!pq.empty()) { Node cur = pq.top(); pq.pop(); - int vertex = cur.vertex; + int id = cur.id; int cost = cur.cost; // Skip if we have already found a better path - if (cost > costs[vertex]) continue; + if (cost > costs[id]) continue; // Traverse all neighbors - for (const Node& neighbor : graph[vertex]) { - int v = neighbor.vertex; - int c = neighbor.cost; - - // Calculate the new cost to reach the neighbor - int nc = costs[vertex] + c; + for (const Node& neighbor : graph[id]) { + int nid = neighbor.id; + int ncost = neighbor.cost; + int new_cost = costs[id] + ncost; // Update the cost if we have found a better path - if (nc < costs[v]) { - costs[v] = nc; - pq.push({v, nc}); + if (new_cost < costs[nid]) { + costs[nid] = new_cost; + pq.push({nid, new_cost}); } } } return costs; } - ``` #### main