-
Notifications
You must be signed in to change notification settings - Fork 0
/
final_imp_inc.c
4063 lines (3450 loc) · 118 KB
/
final_imp_inc.c
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// final not all (6 to 14 are included)
1. HEAPS & AVL (M7)
2. HASHING (M6)
3. DIJKSTRA
4. MST (KRUSKAL, PRIMS)
5. BFS DFS (1. Traversal , 2. isBipartite, 3. longest conc path, 4. connected compontents , 5. shortest cycle , 6. hasCycle, 7. shortest path)
6. Stack(array)
7. Linear QUEUE INT
8. Circular Queue INT
9. LINEAR DEQUE INT
10. CIRCULAR DEQUE INT
11. SINGLE LL (LINEAR)
12. SINGLE LL (CIRCULAR)
13. DOUBLY LL (LINEAR)
14. DOUBLE LL (CIRCULAR)
15. LL FUNCTION (1. sort,2. reverse,3. removeDuplicate,4. rotateClockwise,5. concatTwoLL,6. SplitInHalf,7. SplitInEvenOdd)
16. Binary Tree (functions are mentioned in this topic section)
==========================================================================================================================================
==========================================================================================================================================
=====================================================================
1. M7. HEAPS & AVL
List of Function Names in Module 6
Hashing Functions:
insertChaining (Separate Chaining)
searchChaining
insertLinearProbing (Linear Probing)
searchLinearProbing
insertQuadraticProbing (Quadratic Probing)
searchQuadraticProbing
insertDoubleHashing (Double Hashing)
searchDoubleHashing
rehash
displayHashTable
Extendible Hashing Functions:
initializeExtendibleHashing
insertExtendibleHashing
searchExtendibleHashing
splitBucket
displayExtendibleHashing
List of Function Names in Module 7
Heap Functions:
heapifyDown (Min-Heapify for deletion)
heapifyUp (Min-Heapify for insertion)
insertHeap (Insert element into Min-Heap)
deleteHeapRoot (Delete root from Min-Heap)
displayHeap (Display elements in the heap)
AVL Tree Functions:
newNode (Create a new AVL node)
height (Get the height of an AVL node)
rotateRight (Perform right rotation on an AVL node)
rotateLeft (Perform left rotation on an AVL node)
getBalance (Get the balance factor of an AVL node)
insertAVL (Insert a node into the AVL tree)
deleteAVL (Delete a node from the AVL tree)
minValueNode (Find the node with the smallest value in a subtree)
inorderAVL (Perform in-order traversal of the AVL tree)
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int heap[MAX];
int size = 0;
// Function to restore the heap property after deletion or insertion
void heapifyDown(int i) {
int smallest = i, left = 2 * i + 1, right = 2 * i + 2;
if (left < size && heap[left] < heap[smallest]) smallest = left;
if (right < size && heap[right] < heap[smallest]) smallest = right;
if (smallest != i) {
int temp = heap[i];
heap[i] = heap[smallest];
heap[smallest] = temp;
heapifyDown(smallest);
}
}
void heapifyUp(int i) {
int parent = (i - 1) / 2;
if (i && heap[i] < heap[parent]) {
int temp = heap[i];
heap[i] = heap[parent];
heap[parent] = temp;
heapifyUp(parent);
}
}
void insertHeap(int val) {
if (size == MAX) {
printf("Heap overflow\n");
return;
}
heap[size++] = val;
heapifyUp(size - 1);
}
void deleteHeapRoot() {
if (size == 0) {
printf("Heap underflow\n");
return;
}
heap[0] = heap[--size];
heapifyDown(0);
}
void displayHeap() {
printf("Heap: ");
for (int i = 0; i < size; i++) printf("%d ", heap[i]);
printf("\n");
}
typedef struct AVLNode {
int key, height;
struct AVLNode *left, *right;
} AVLNode;
AVLNode* newNode(int key) {
AVLNode* node = (AVLNode*)malloc(sizeof(AVLNode));
node->key = key;
node->left = node->right = NULL;
node->height = 1;
return node;
}
int height(AVLNode* n) {
return n ? n->height : 0;
}
AVLNode* rotateRight(AVLNode* y) {
AVLNode* x = y->left;
AVLNode* T2 = x->right;
x->right = y;
y->left = T2;
y->height = 1 + (height(y->left) > height(y->right) ? height(y->left) : height(y->right));
x->height = 1 + (height(x->left) > height(x->right) ? height(x->left) : height(x->right));
return x;
}
AVLNode* rotateLeft(AVLNode* x) {
AVLNode* y = x->right;
AVLNode* T2 = y->left;
y->left = x;
x->right = T2;
x->height = 1 + (height(x->left) > height(x->right) ? height(x->left) : height(x->right));
y->height = 1 + (height(y->left) > height(y->right) ? height(y->left) : height(y->right));
return y;
}
int getBalance(AVLNode* n) {
return n ? height(n->left) - height(n->right) : 0;
}
AVLNode* insertAVL(AVLNode* node, int key) {
if (!node) return newNode(key);
if (key < node->key) node->left = insertAVL(node->left, key);
else if (key > node->key) node->right = insertAVL(node->right, key);
else return node;
node->height = 1 + (height(node->left) > height(node->right) ? height(node->left) : height(node->right));
int balance = getBalance(node);
if (balance > 1 && key < node->left->key) return rotateRight(node);
if (balance < -1 && key > node->right->key) return rotateLeft(node);
if (balance > 1 && key > node->left->key) {
node->left = rotateLeft(node->left);
return rotateRight(node);
}
if (balance < -1 && key < node->right->key) {
node->right = rotateRight(node->right);
return rotateLeft(node);
}
return node;
}
AVLNode* minValueNode(AVLNode* node) {
AVLNode* current = node;
while (current->left) current = current->left;
return current;
}
AVLNode* deleteAVL(AVLNode* root, int key) {
if (!root) return root;
if (key < root->key) root->left = deleteAVL(root->left, key);
else if (key > root->key) root->right = deleteAVL(root->right, key);
else {
if (!root->left || !root->right) {
AVLNode* temp = root->left ? root->left : root->right;
if (!temp) {
temp = root;
root = NULL;
} else *root = *temp;
free(temp);
} else {
AVLNode* temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteAVL(root->right, temp->key);
}
}
if (!root) return root;
root->height = 1 + (height(root->left) > height(root->right) ? height(root->left) : height(root->right));
int balance = getBalance(root);
if (balance > 1 && getBalance(root->left) >= 0) return rotateRight(root);
if (balance > 1 && getBalance(root->left) < 0) {
root->left = rotateLeft(root->left);
return rotateRight(root);
}
if (balance < -1 && getBalance(root->right) <= 0) return rotateLeft(root);
if (balance < -1 && getBalance(root->right) > 0) {
root->right = rotateRight(root->right);
return rotateLeft(root);
}
return root;
}
void inorderAVL(AVLNode* root) {
if (!root) return;
inorderAVL(root->left);
printf("%d ", root->key);
inorderAVL(root->right);
}
int main() {
AVLNode* root = NULL;
// Min-Heap Operations
insertHeap(10);
insertHeap(20);
insertHeap(5);
displayHeap();
deleteHeapRoot();
displayHeap();
// AVL Tree Operations
root = insertAVL(root, 10);
root = insertAVL(root, 20);
root = insertAVL(root, 5);
root = insertAVL(root, 15);
printf("Inorder AVL after insertion: ");
inorderAVL(root);
printf("\n");
root = deleteAVL(root, 20);
printf("Inorder AVL after deletion: ");
inorderAVL(root);
printf("\n");
return 0;
}
=====================================================================
2. M6. HASHING
Hashing Functions:
insertChaining (Separate Chaining)
searchChaining
insertLinearProbing (Linear Probing)
searchLinearProbing
insertQuadraticProbing (Quadratic Probing)
searchQuadraticProbing
insertDoubleHashing (Double Hashing)
searchDoubleHashing
rehash
displayHashTable
Extendible Hashing Functions:
initializeExtendibleHashing
insertExtendibleHashing
searchExtendibleHashing
splitBucket
displayExtendibleHashing
### Module 6: Hashing
#### Complete Code for Hashing (All Techniques)
```c
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
#define BUCKET_SIZE 2
#define GLOBAL_DEPTH 2
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* hashTableChaining[SIZE];
int hashTableLinear[SIZE];
int hashTableQuadratic[SIZE];
int hashTableDoubleHashing[SIZE];
typedef struct Bucket {
int keys[BUCKET_SIZE];
int count;
} Bucket;
Bucket* directory[1 << GLOBAL_DEPTH];
void initHashTables() {
for (int i = 0; i < SIZE; i++) {
hashTableChaining[i] = NULL;
hashTableLinear[i] = -1;
hashTableQuadratic[i] = -1;
hashTableDoubleHashing[i] = -1;
}
for (int i = 0; i < (1 << GLOBAL_DEPTH); i++) {
directory[i] = (Bucket*)malloc(sizeof(Bucket));
directory[i]->count = 0;
}
}
int hashFunction(int key) {
return key % SIZE;
}
void insertChaining(int key) {
int index = hashFunction(key);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = key;
newNode->next = hashTableChaining[index];
hashTableChaining[index] = newNode;
}
void insertLinearProbing(int key) {
int index = hashFunction(key);
while (hashTableLinear[index] != -1) {
index = (index + 1) % SIZE;
}
hashTableLinear[index] = key;
}
int quadraticProbing(int key, int i) {
return (key % SIZE + i * i) % SIZE;
}
void insertQuadraticProbing(int key) {
int i = 0, index;
while (i < SIZE) {
index = quadraticProbing(key, i);
if (hashTableQuadratic[index] == -1) {
hashTableQuadratic[index] = key;
return;
}
i++;
}
printf("Hash table overflow! Could not insert %d\n", key);
}
int doubleHash(int key, int i) {
int hash1 = key % SIZE;
int hash2 = 7 - (key % 7);
return (hash1 + i * hash2) % SIZE;
}
void insertDoubleHashing(int key) {
int i = 0, index;
while (i < SIZE) {
index = doubleHash(key, i);
if (hashTableDoubleHashing[index] == -1) {
hashTableDoubleHashing[index] = key;
return;
}
i++;
}
printf("Hash table overflow! Could not insert %d\n", key);
}
void insertExtendible(int key) {
int index = key % (1 << GLOBAL_DEPTH);
Bucket* bucket = directory[index];
if (bucket->count < BUCKET_SIZE) {
bucket->keys[bucket->count++] = key;
} else {
printf("Bucket overflow! Key %d could not be inserted.\n", key);
}
}
void displayHashTables() {
printf("\nSeparate Chaining:\n");
for (int i = 0; i < SIZE; i++) {
printf("Index %d: ", i);
Node* temp = hashTableChaining[i];
while (temp) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
printf("\nLinear Probing:\n");
for (int i = 0; i < SIZE; i++) {
if (hashTableLinear[i] != -1)
printf("Index %d: %d\n", i, hashTableLinear[i]);
else
printf("Index %d: EMPTY\n", i);
}
printf("\nQuadratic Probing:\n");
for (int i = 0; i < SIZE; i++) {
if (hashTableQuadratic[i] != -1)
printf("Index %d: %d\n", i, hashTableQuadratic[i]);
else
printf("Index %d: EMPTY\n", i);
}
printf("\nDouble Hashing:\n");
for (int i = 0; i < SIZE; i++) {
if (hashTableDoubleHashing[i] != -1)
printf("Index %d: %d\n", i, hashTableDoubleHashing[i]);
else
printf("Index %d: EMPTY\n", i);
}
printf("\nExtendible Hashing:\n");
for (int i = 0; i < (1 << GLOBAL_DEPTH); i++) {
printf("Bucket %d: ", i);
for (int j = 0; j < directory[i]->count; j++) {
printf("%d ", directory[i]->keys[j]);
}
printf("\n");
}
}
int main() {
initHashTables();
insertChaining(15);
insertChaining(25);
insertLinearProbing(15);
insertLinearProbing(25);
insertQuadraticProbing(15);
insertQuadraticProbing(25);
insertDoubleHashing(15);
insertDoubleHashing(25);
insertExtendible(15);
insertExtendible(25);
displayHashTables();
return 0;
}
```
=====================================================================
3. DIJKSTRA
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
#define MAX 100
// Function to find the unvisited vertex with the minimum distance
int findMin(int dist[], bool visited[], int v) {
int min = INT_MAX, minIdx = -1;
for (int i = 0; i < v; i++) {
if (dist[i] < min && !visited[i]) {
min = dist[i];
minIdx = i;
}
}
return minIdx;
}
// Dijkstra's algorithm to find shortest path from source to destination
void dijkstra(int graph[MAX][MAX], int v, int src, int dest) {
int dist[MAX], prev[MAX];
bool visited[MAX] = { false };
// Initialize distances and previous vertices
for (int i = 0; i < v; i++) {
dist[i] = INT_MAX;
prev[i] = -1;
}
dist[src] = 0;
// Dijkstra's algorithm main loop
for (int count = 0; count < v - 1; count++) {
int x = findMin(dist, visited, v);
visited[x] = true;
for (int y = 0; y < v; y++) {
if (graph[x][y] && !visited[y] && dist[x] != INT_MAX && dist[x] + graph[x][y] < dist[y]) {
dist[y] = dist[x] + graph[x][y];
prev[y] = x;
}
}
}
// Check if destination is reachable
if (dist[dest] == INT_MAX) {
printf("No path found\n");
} else {
// Backtrack to find path from destination to source
int path[MAX], pathLen = 0;
for (int idx = dest; idx != -1; idx = prev[idx]) {
path[pathLen++] = idx;
}
// Print shortest path
printf("Shortest path: %d", src);
for (int i = pathLen - 2; i >= 0; i--) {
printf(" -> %d", path[i]);
}
printf("\nShortest distance: %d\n", dist[dest]);
}
}
int main() {
int v, e;
scanf("%d %d", &v, &e); // Number of vertices and edges
int graph[MAX][MAX] = {0}; // Initialize graph with 0s
// Input edges
for (int i = 0; i < e; i++) {
int a, b, w;
scanf("%d %d %d", &a, &b, &w);
graph[a][b] = w;
graph[b][a] = w;
}
int src, dest;
scanf("%d %d", &src, &dest); // Input source and destination
dijkstra(graph, v, src, dest);
return 0;
}
/*
Input 1 :
4
5
0 1 2
0 2 4
1 2 1
1 3 7
2 3 3
0
3
Output 1 :
Shortest path: 0 -> 1 -> 2 -> 3
Shortest distance: 6
*/
=====================================================================
4. MST
1>>>> KRUSKAL
#include <stdio.h>
#include <stdlib.h>
#define MAX 100 // Maximum number of vertices in the graph
#define INF 999999 // Representation of no edge between vertices
// Structure to represent an edge with a source, destination, and weight
struct Edge {
int src, dest, weight;
};
// Structure to represent subsets for union-find
// Each subset has a parent (for find operation) and rank (for union by rank)
struct Subset {
int parent, rank;
};
// Function to find the root of a subset (with path compression to optimize performance)
int find(struct Subset subsets[], int i) {
// If i is not the root, find its parent recursively
if (subsets[i].parent != i) {
subsets[i].parent = find(subsets, subsets[i].parent); // Path compression
}
return subsets[i].parent;
}
// Function to union two subsets by rank
// Attach the tree with the smaller rank to the tree with the larger rank
void Union(struct Subset subsets[], int x, int y) {
int xroot = find(subsets, x); // Find root of subset x
int yroot = find(subsets, y); // Find root of subset y
// Attach smaller rank tree under root of the higher rank tree
if (subsets[xroot].rank < subsets[yroot].rank) {
subsets[xroot].parent = yroot;
} else if (subsets[xroot].rank > subsets[yroot].rank) {
subsets[yroot].parent = xroot;
} else {
// If ranks are equal, make one root and increment its rank
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
// Comparator function for qsort to sort edges by their weights in ascending order
int compareEdges(const void* a, const void* b) {
struct Edge* edgeA = (struct Edge*)a;
struct Edge* edgeB = (struct Edge*)b;
return edgeA->weight - edgeB->weight;
}
// Function to implement Kruskal's algorithm for finding the MST
void kruskal(int graph[MAX][MAX], int V) {
struct Edge edges[MAX * MAX]; // Array to hold all edges of the graph
int edgeCount = 0; // Counter to keep track of the number of edges
// Convert adjacency matrix into an edge list
for (int i = 0; i < V; i++) {
for (int j = i + 1; j < V; j++) {
if (graph[i][j] != 0 && graph[i][j] != INF) { // Check if edge exists
edges[edgeCount++] = (struct Edge){i, j, graph[i][j]}; // Store edge in list
}
}
}
// Sort edges by their weights in ascending order
qsort(edges, edgeCount, sizeof(edges[0]), compareEdges);
// Create subsets for each vertex (for union-find)
struct Subset subsets[MAX];
for (int i = 0; i < V; i++) {
subsets[i].parent = i; // Initially, each vertex is its own parent
subsets[i].rank = 0; // Initial rank is 0
}
// Array to store edges included in the MST
struct Edge result[MAX];
int e = 0; // Counter for number of edges in the MST
// Process each edge in sorted order
for (int i = 0; i < edgeCount && e < V - 1; i++) {
struct Edge nextEdge = edges[i]; // Get the next edge with minimum weight
// Find the root of the subsets of both vertices of the edge
int x = find(subsets, nextEdge.src);
int y = find(subsets, nextEdge.dest);
// If including this edge doesn't form a cycle, add it to the MST
if (x != y) {
result[e++] = nextEdge; // Include edge in MST
Union(subsets, x, y); // Union the subsets
}
}
// Print the MST
printf("Edges in the Minimum Spanning Tree:\n");
for (int i = 0; i < e; i++) {
printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].weight);
}
}
int main() {
int V;
int graph[MAX][MAX];
// Input number of vertices
printf("Enter the number of vertices: ");
scanf("%d", &V);
// Input the adjacency matrix
// Use INF (999999) to represent no edge between vertices
printf("Enter the adjacency matrix (enter %d for no edge):\n", INF);
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
scanf("%d", &graph[i][j]);
}
}
// Execute Kruskal's algorithm to find the MST
kruskal(graph, V);
return 0;
}
/*
input
Enter the number of vertices and edges: 4 5
Enter each edge (source, destination, weight):
0 1 10
0 2 6
0 3 5
1 3 15
2 3 4
output
Edge Weight
2 - 3 4
0 - 3 5
0 - 1 10
*/
2>>> PRIMS
#include <stdio.h>
#include <stdbool.h>
#define MAX 100 // Maximum number of vertices
#define INF 999999 // Representation of no edge between vertices
// Function to find the vertex with the minimum key value from the set of vertices not yet included in MST
int minKey(int key[], bool mstSet[], int V) {
int min = INF, minIndex;
// Iterate over all vertices to find the minimum key value
for (int v = 0; v < V; v++) {
// Update min if key[v] is smaller and v is not in the MST yet
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex; // Return index of vertex with minimum key value
}
// Function to print the constructed MST stored in parent[]
void printMST(int parent[], int graph[MAX][MAX], int V) {
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
// Print each edge and its weight
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
}
// Function to implement Prim's algorithm for MST
void primMST(int graph[MAX][MAX], int V) {
int parent[MAX]; // Array to store the MST (parent array)
int key[MAX]; // Key values used to pick the minimum weight edge
bool mstSet[MAX]; // Boolean array to represent set of vertices included in MST
// Initialize key values as INF and mstSet as false for all vertices
for (int i = 0; i < V; i++) {
key[i] = INF; // Set initial key value to infinity
mstSet[i] = false; // Mark all vertices as not included in MST
}
key[0] = 0; // Make key of the first vertex as 0 so that it is picked first
parent[0] = -1; // First vertex is always the root of the MST
// The MST will have exactly V-1 edges, so we iterate V-1 times
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet, V); // Pick vertex u with the smallest key value not in MST
mstSet[u] = true; // Include vertex u in MST
// Update the key and parent for the adjacent vertices of u
for (int v = 0; v < V; v++) {
// Update key[v] only if graph[u][v] is non-zero (edge exists),
// v is not yet included in MST, and the new key is smaller
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u; // Set u as parent of v in MST
key[v] = graph[u][v]; // Update key with weight of the edge u-v
}
}
}
// Print the MST using the parent array
printMST(parent, graph, V);
}
int main() {
int V;
int graph[MAX][MAX];
// Input the number of vertices in the graph
printf("Enter the number of vertices: ");
scanf("%d", &V);
// Input the adjacency matrix, using INF (999999) to indicate no edge
printf("Enter the adjacency matrix (enter %d for no edge):\n", INF);
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
scanf("%d", &graph[i][j]);
}
}
// Run Prim's algorithm to find the MST
primMST(graph, V);
return 0;
}
/**
input
Enter the number of vertices: 4
Enter the adjacency matrix (enter 999999 for no edge):
0 4 0 999999
4 0 8 11
0 8 0 7
999999 11 7 0
output
Edge Weight
0 - 1 4
0 - 2 0
2 - 3 7
*/
=====================================================================
5. BFS DFS (1. Traversal , 2. isBipartite, 3.longest conc path, 4.connected compontents , 5. shortest cycle , 6. hasCycle, 7. shortest path)
1>>>>
#include <stdio.h>
#define MAX 100
// BFS function for a single component
void bfs(int graph[MAX][MAX], int visited[], int start, int vertices) {
int queue[MAX], front = 0, rear = 0;
visited[start] = 1;
queue[rear++] = start;
while (front < rear) {
int currentVertex = queue[front++];
printf("%d ", currentVertex);
for (int i = 0; i < vertices; i++) {
if (graph[currentVertex][i] == 1 && !visited[i]) {
visited[i] = 1;
queue[rear++] = i;
}
}
}
}
// DFS function for a single component
void dfs(int graph[MAX][MAX], int visited[], int start, int v) {
visited[start] = 1;
printf("%d ", start);
for(int j = 0; j < v; j++) {
if(graph[start][j] == 1 && !visited[j]) {
dfs(graph, visited, j, v);
}
}
}
int main() {
int vertices, edges;
int graph[MAX][MAX] = {0}; // Adjacency matrix
int visited[MAX] = {0}; // Visited array for both BFS and DFS
// Input number of vertices and edges
scanf("%d %d", &vertices, &edges);
// Input edges
for (int i = 0; i < edges; i++) {
int src, dest;
scanf("%d %d", &src, &dest);
graph[src][dest] = 1;
graph[dest][src] = 1; // For undirected graph
}
// DFS traversal for all components
printf("DFS for all components:\n");
for (int i = 0; i < vertices; i++) {
if (!visited[i]) {
dfs(graph, visited, i, vertices);
printf("\n");
}
}
// Reset visited for BFS
for (int i = 0; i < vertices; i++) visited[i] = 0;
// BFS traversal for all components
/* if you start from any particular vertex
int start;
scanf("%d",&start);
bfs(graph,visited,start,v);
*/
// disconnected graph
printf("BFS for all components:\n");
for (int i = 0; i < vertices; i++) {
if (!visited[i]) {
bfs(graph, visited, i, vertices);
printf("\n");
}
}
return 0;
}
/*
input :
6 7
0 1
0 2
1 3
1 4
2 4
3 5
4 5
0
*/
2>>>>>>>
#include <stdio.h>
#define MAX 6
// Function to check if the graph is bipartite using BFS
int isBipartiteBFS(int graph[MAX][MAX], int v, int start) {
int color[MAX];
// Initialize all vertices with color -1, which means "uncolored"
for (int i = 0; i < v; i++) {
color[i] = -1;
}
color[start] = 1; // Start coloring the starting vertex with color 1
int queue[MAX], front = 0, rear = 0;
queue[rear++] = start;
// Process nodes in the queue
while (front < rear) {
int u = queue[front++];
// Check for a self-loop
if (graph[u][u] == 1) return 0;
// Explore all adjacent vertices
for (int adj = 0; adj < v; adj++) {
if (graph[u][adj] == 1) { // There is an edge
if (color[adj] == -1) { // If the adjacent vertex is not colored
color[adj] = 1 - color[u]; // Assign opposite color
queue[rear++] = adj;
} else if (color[adj] == color[u]) { // If adjacent vertices have the same color
return 0; // Graph is not bipartite
}
}
}
}
return 1; // Graph is bipartite
}
// Helper function for DFS
int dfsCheck(int graph[MAX][MAX], int color[], int u, int v) {
// Explore all adjacent vertices
for (int adj = 0; adj < v; adj++) {
if (graph[u][adj] == 1) { // There is an edge
if (color[adj] == -1) { // If the adjacent vertex is not colored
color[adj] = 1 - color[u]; // Assign opposite color
if (!dfsCheck(graph, color, adj, v)) {
return 0; // Graph is not bipartite
}
} else if (color[adj] == color[u]) { // If adjacent vertices have the same color
return 0; // Graph is not bipartite
}
}
}
return 1; // Continue checking
}
// Function to check if the graph is bipartite using DFS
int isBipartiteDFS(int graph[MAX][MAX], int v, int start) {
int color[MAX];
// Initialize all vertices with color -1, meaning "uncolored"
for (int i = 0; i < v; i++) {
color[i] = -1;
}
color[start] = 1; // Start coloring the starting vertex with color 1
return dfsCheck(graph, color, start, v);
}
int main() {
int v;
printf("Enter the number of vertices: ");
scanf("%d", &v);
int graph[MAX][MAX];
printf("Enter the adjacency matrix of the graph:\n");