-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriorityqueue.c
More file actions
67 lines (55 loc) · 1.47 KB
/
Copy pathpriorityqueue.c
File metadata and controls
67 lines (55 loc) · 1.47 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
#define MAX_HEAP_SIZE 1000
typedef struct {
int x, y; // Node coordinates
float f; // Priority (f = g + h)
} Node;
typedef struct {
Node heap[MAX_HEAP_SIZE];
int size;
} PriorityQueue;
// Function to swap two integers
void swap(Node* a, Node* b) {
Node temp = *a;
*a = *b;
*b = temp;
}
// Add an item to the queue
void pushPQ(PriorityQueue* pq, int x, int y, float f) {
if (pq->size >= MAX_HEAP_SIZE) {
printf("Priority queue is full\n");
return;
}
int i = pq->size++;
pq->heap[i].x = x;
pq->heap[i].y = y;
pq->heap[i].f = f;
// Maintain heap property (ascending)
while (i>0 && pq->heap[(i-1)/2].f > pq->heap[i].f) {
swap(&pq->heap[i], &pq->heap[(i-1)/2]);
i = (i-1)/2;
}
}
Node popPQ(PriorityQueue* pq) {
if (pq->size <= 0) {
printf("Priority queue is empty\n");
exit(1);
}
Node min = pq->heap[0];
pq->heap[0] = pq->heap[--pq->size];
// Maintain heap property (descending)
int i = 0;
while (1) {
int left = 2*i + 1;
int right = 2*i + 2;
int smallest = i;
if (left < pq->size && pq->heap[left].f < pq->heap[smallest].f) smallest = left;
if (right < pq->size && pq->heap[right].f < pq->heap[smallest].f) smallest = right;
if (smallest == i) break;
swap(&pq->heap[i], &pq->heap[smallest]);
i = smallest;
}
return min;
}
int isEmpty(PriorityQueue* pq) {
return pq->size == 0;
}