-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfibonacci_dijkstra.cpp
More file actions
103 lines (81 loc) · 2.92 KB
/
fibonacci_dijkstra.cpp
File metadata and controls
103 lines (81 loc) · 2.92 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "fibonacciheap.h"
#include "binaryheap.h"
// Dijkstra's algorithm using Fibonacci heap
void dijkstra_fibonacci(Graph* graph, int src, int* dist, int* prev) {
int num_nodes = graph->num_nodes;
// Initialize distance and predecessor arrays
for (int i = 0; i < num_nodes; i++) {
dist[i] = INF;
prev[i] = -1;
}
dist[src] = 0;
// Create Fibonacci heap and node pointer array
FibonacciHeap* heap = create_fib_heap();
FibNode** node_ptrs = (FibNode**)malloc(num_nodes * sizeof(FibNode*));
// Initialize node pointer array
for (int i = 0; i < num_nodes; i++) {
node_ptrs[i] = NULL;
}
// Insert source node
node_ptrs[src] = create_fib_node(src, 0);
fib_heap_insert(heap, node_ptrs[src]);
// Record whether a node has been processed
int* visited = (int*)calloc(num_nodes, sizeof(int));
while (!is_fib_heap_empty(heap)) {
// Extract node with minimum distance
FibNode* min_node = fib_heap_extract_min(heap);
int u = min_node->vertex;
// Skip processed nodes or invalid distances
if (visited[u] || min_node->distance == INF) {
free(min_node);
continue;
}
visited[u] = 1;
// Traverse all neighbors
AdjNode* neighbor = graph->adj_list[u];
while (neighbor != NULL) {
int v = neighbor->vertex;
int weight = neighbor->weight;
if (!visited[v]) {
int new_dist = dist[u] + weight;
// If a shorter path is found
if (new_dist < dist[v]) {
dist[v] = new_dist;
prev[v] = u;
if (node_ptrs[v] == NULL) {
// First visit to this node, insert into heap
node_ptrs[v] = create_fib_node(v, new_dist);
fib_heap_insert(heap, node_ptrs[v]);
}
else {
// Update node distance in heap
fib_heap_decrease_key(heap, node_ptrs[v], new_dist);
}
}
}
neighbor = neighbor->next;
}
// Free processed node
free(min_node);
node_ptrs[u] = NULL;
}
// Clean up memory
free(visited);
free(node_ptrs);
free_fib_heap(heap);
}
// Compute shortest path to a specific target using Fibonacci heap
int shortest_path_length_fibonacci(Graph* graph, int src, int target, int* path, int* path_length) {
int num_nodes = graph->num_nodes;
int* dist = (int*)malloc(num_nodes * sizeof(int));
int* prev = (int*)malloc(num_nodes * sizeof(int));
dijkstra_fibonacci(graph, src, dist, prev);
int distance = dist[target];
if (distance != INF)
reconstruct_path(prev, target, path, path_length);
else
*path_length = 0;
free(dist);
free(prev);
return distance;
}