0% found this document useful (0 votes)
7 views21 pages

DS Practicals

This document contains condensed C programs for various data structures and algorithms, formatted for PDF readability. It includes implementations for searching elements in arrays, insertion and deletion in arrays, binary search, sorting algorithms (bubble sort and selection sort), linked lists (linear, circular, and doubly), sparse matrix representation, and polynomial representation using linked lists. Each section provides code examples and explanations for the respective data structure or algorithm.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views21 pages

DS Practicals

This document contains condensed C programs for various data structures and algorithms, formatted for PDF readability. It includes implementations for searching elements in arrays, insertion and deletion in arrays, binary search, sorting algorithms (bubble sort and selection sort), linked lists (linear, circular, and doubly), sparse matrix representation, and polynomial representation using linked lists. Each section provides code examples and explanations for the respective data structure or algorithm.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

C Programs for Data Structures and Algorithms

(Condensed & PDF-Friendly v3)


This document provides condensed C programs for various data structures and
algorithms, formatted to improve PDF readability.

1. Search Element and Print Occurrences in Array


Searches for an element in an array and prints its total occurrences.
#include <stdio.h>

void searchElementAndCount(int arr[], int size, int elementToSearch) {


int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == elementToSearch) {
count++;
}
}
if (count > 0) {
printf("Element %d found %d time(s).\n", elementToSearch, count);
} else {
printf("Element %d not found.\n", elementToSearch);
}
}

int main() {
int arr[] = {1, 2, 3, 4, 2, 5, 2, 6};
int size = sizeof(arr) / sizeof(arr[0]);
searchElementAndCount(arr, size, 2);
searchElementAndCount(arr, size, 7);
return 0;
}

2. Insert and Delete Elements in Array


Inserts and deletes elements from an array at specified positions.
#include <stdio.h>

void displayArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

1
int insertElement(int arr[], int size, int capacity, int element, int position) {
if (size >= capacity || position < 0 || position > size) {
printf("Cannot insert.\n");
return size;
}
for (int i = size - 1; i >= position; i--) {
arr[i + 1] = arr[i];
}
arr[position] = element;
return size + 1;
}

int deleteElement(int arr[], int size, int position) {


if (size == 0 || position < 0 || position >= size) {
printf("Cannot delete.\n");
return size;
}
for (int i = position; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
return size - 1;
}

int main() {
int arr[10] = {10, 20, 30, 40, 50};
int size = 5;
printf("Original: "); displayArray(arr, size);
size = insertElement(arr, size, 10, 25, 2);
printf("After insert: "); displayArray(arr, size);
size = deleteElement(arr, size, 1);
printf("After delete: "); displayArray(arr, size);
return 0;
}

3. Binary Search
Performs binary search on a sorted array.
#include <stdio.h>

int binarySearch(int arr[], int size, int element) {


int low = 0, high = size - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == element) {
return mid;

2
}
if (arr[mid] < element) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}

int main() {
int arr[] = {10, 20, 30, 40, 50, 60};
int size = sizeof(arr) / sizeof(arr[0]);
int element = 30;
int result = binarySearch(arr, size, element);
if (result != -1) {
printf("Element %d found at index %d.\n", element, result);
} else {
printf("Element %d not found.\n", element);
}
return 0;
}

4. Bubble Sort
Sorts an array using Bubble Sort.
#include <stdio.h>

void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; }

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) printf("%d ", arr[i]);
printf("\n");
}

3
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: "); printArray(arr, n);
return 0;
}

5. Selection Sort
Sorts an array using Selection Sort.
#include <stdio.h>

void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; }

void selectionSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
if(min_idx != i) {
swap(&arr[min_idx], &arr[i]);
}
}
}

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = {64, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: "); printArray(arr, n);
return 0;
}

6. Linear Linked List Operations


Implements a linear linked list: traverse, search, insert, delete, reverse.

4
#include <stdio.h>
#include <stdlib.h>

struct Node { int data; struct Node* next; };

struct Node* createNode(int data) {


struct Node* nn = (struct Node*)malloc(sizeof(struct Node));
nn->data = data; nn->next = NULL; return nn;
}

struct Node* insertAtBeginning(struct Node* head, int data) {


struct Node* nn = createNode(data);
nn->next = head; return nn;
}

void traverseList(struct Node* head) {


struct Node* temp = head;
while (temp != NULL) { printf("%d -> ", temp->data); temp = temp->next; }
printf("NULL\n");
}

struct Node* searchElement(struct Node* head, int value) {


struct Node* temp = head; int pos = 0;
while (temp != NULL) {
if (temp->data == value) {
printf("Found %d at pos %d.\n", value, pos);
return temp;
}
temp = temp->next; pos++;
}
printf("%d not found.\n", value); return NULL;
}

struct Node* deleteByValue(struct Node* head, int value) {


struct Node *temp = head, *prev = NULL;
if (temp != NULL && temp->data == value) {
head = temp->next; free(temp); return head;
}
while (temp != NULL && temp->data != value) {
prev = temp; temp = temp->next;
}
if (temp == NULL) return head;
prev->next = temp->next; free(temp); return head;
}

struct Node* reverseList(struct Node* head) {

5
struct Node *prev = NULL, *current = head, *nextNode = NULL;
while (current != NULL) {
nextNode = current->next; current->next = prev;
prev = current; current = nextNode;
}
return prev;
}

int main() {
struct Node* head = NULL;
head = insertAtBeginning(head, 30);
head = insertAtBeginning(head, 20);
head = insertAtBeginning(head, 10);
printf("List: "); traverseList(head);
searchElement(head, 20);
head = deleteByValue(head, 20);
printf("After deleting 20: "); traverseList(head);
head = reverseList(head);
printf("Reversed list: "); traverseList(head);
while(head != NULL){
struct Node* temp = head;
head = head->next;
free(temp);
}
return 0;
}

7. Circular Linked List Operations (Insert and Delete)


Implements a circular linked list: node insert and delete.
#include <stdio.h>
#include <stdlib.h>

struct NodeCLL { int data; struct NodeCLL* next; }; // Renamed

struct NodeCLL* createNodeCLL(int data){


struct NodeCLL* nn = (struct NodeCLL*)malloc(sizeof(struct NodeCLL));
nn->data = data; nn->next = nn; return nn;
}

void displayCLL(struct NodeCLL* last) {


if (last == NULL) { printf("Empty.\n"); return; }
struct NodeCLL* temp = last->next;
do { printf("%d -> ", temp->data); temp = temp->next; } while (temp != last->next);
printf("(head: %d)\n", last->next->data);

6
}

struct NodeCLL* insertAtEndCLL(struct NodeCLL* last, int data) {


struct NodeCLL* nn = createNodeCLL(data);
if (last == NULL) return nn;
nn->next = last->next; last->next = nn; return nn;
}

struct NodeCLL* deleteFromBeginningCLL(struct NodeCLL* last) {


if (last == NULL) return NULL;
struct NodeCLL* head = last->next;
if (last == head) { free(last); return NULL; }
last->next = head->next; free(head); return last;
}

int main() {
struct NodeCLL* last = NULL;
last = insertAtEndCLL(last, 10);
last = insertAtEndCLL(last, 20);
last = insertAtEndCLL(last, 30);
printf("CLL: "); displayCLL(last);
last = deleteFromBeginningCLL(last);
printf("After delete: "); displayCLL(last);
if (last) {
struct NodeCLL* curr = last->next;
struct NodeCLL* next_node;
if (curr == last) { // Single node case after deletion
free(curr);
last = NULL;
} else {
do {
next_node = curr->next;
free(curr);
curr = next_node;
} while (curr != last); // Free until last node
free(last); // Free the last node itself
last = NULL;
}
}
return 0;
}

8. Doubly Linked List Operations (Insert and Delete)


Implements a doubly linked list: node insert and delete.

7
#include <stdio.h>
#include <stdlib.h>

struct NodeDLL { int data; struct NodeDLL *prev, *next; };

struct NodeDLL* createNodeDLL(int data) {


struct NodeDLL* nn = (struct NodeDLL*)malloc(sizeof(struct NodeDLL));
nn->data = data; nn->prev = nn->next = NULL; return nn;
}

void displayDLL(struct NodeDLL* head) {


struct NodeDLL* temp = head; printf("NULL <-> ");
while (temp != NULL) { printf("%d <-> ", temp->data); temp = temp->next; }
printf("NULL\n");
}

struct NodeDLL* insertAtEndDLL(struct NodeDLL* head, int data) {


struct NodeDLL* nn = createNodeDLL(data);
if (head == NULL) return nn;
struct NodeDLL* temp = head;
while (temp->next != NULL) temp = temp->next;
temp->next = nn; nn->prev = temp; return head;
}

struct NodeDLL* deleteFromEndDLL(struct NodeDLL* head) {


if (head == NULL) return NULL;
if (head->next == NULL) { free(head); return NULL; }
struct NodeDLL* temp = head;
while (temp->next != NULL) temp = temp->next;
temp->prev->next = NULL; free(temp); return head;
}

int main() {
struct NodeDLL* head = NULL;
head = insertAtEndDLL(head, 10);
head = insertAtEndDLL(head, 20);
head = insertAtEndDLL(head, 30);
printf("DLL: "); displayDLL(head);
head = deleteFromEndDLL(head);
printf("After delete: "); displayDLL(head);
while(head != NULL){
struct NodeDLL* temp = head;
head = head->next;
free(temp);
}
return 0;

8
}

9. Sparse Matrix Representation using Linked List


Represents a sparse matrix using a linked list.
#include <stdio.h>
#include <stdlib.h>

struct SparseNode { int row, col, value; struct SparseNode* next; };

struct SparseNode* createSparseNode(int r, int c, int val) {


struct SparseNode* nn = (struct SparseNode*)malloc(sizeof(struct SparseNode));
nn->row = r; nn->col = c; nn->value = val; nn->next = NULL; return nn;
}

struct SparseNode* addNonZero(struct SparseNode* head, int r, int c, int val) {


if (val == 0) return head;
struct SparseNode* nn = createSparseNode(r, c, val);
if (!head || head->row > r || (head->row == r && head->col > c)) {
nn->next = head; return nn;
}
struct SparseNode* curr = head;
while (curr->next &&
(curr->next->row < r || (curr->next->row == r && curr->next->col < c))) {
curr = curr->next;
}
nn->next = curr->next; curr->next = nn; return head;
}

void displaySparse(struct SparseNode* head, int R, int C) {


printf("Sparse List (row,col,val):\n");
struct SparseNode* temp_list = head;
while(temp_list) {
printf("(%d,%d,%d) ",temp_list->row,temp_list->col,temp_list->value);
temp_list=temp_list->next;
}
printf("\nMatrix form:\n");
struct SparseNode* temp_matrix = head;
for (int i=0; i<R; i++) {
for (int j=0; j<C; j++) {
if (temp_matrix && temp_matrix->row==i && temp_matrix->col==j) {
printf("%d\t", temp_matrix->value);
temp_matrix=temp_matrix->next;
} else {
printf("0\t");

9
}
}
printf("\n");
}
}

int main() {
struct SparseNode* sm_head = NULL;
int mat[3][4] = {{0,5,0,0},{0,0,1,0},{2,0,0,8}};
int R=3, C=4;
for(int i=0; i<R; i++) {
for(int j=0; j<C; j++) {
sm_head = addNonZero(sm_head,i,j,mat[i][j]);
}
}
displaySparse(sm_head, R, C);
while(sm_head){
struct SparseNode* temp_free = sm_head;
sm_head = sm_head->next;
free(temp_free);
}
return 0;
}

10. Polynomial Representation using Linked List


Represents a polynomial using a linked list.
#include <stdio.h>
#include <stdlib.h>

struct Term { int coeff, exp; struct Term* next; };

struct Term* createTerm(int c, int e) {


struct Term* nt = (struct Term*)malloc(sizeof(struct Term));
nt->coeff = c; nt->exp = e; nt->next = NULL; return nt;
}

struct Term* addTerm(struct Term* poly, int c, int e) {


if (c == 0) return poly;
struct Term* nt = createTerm(c, e);
struct Term* curr = poly;
struct Term* prev = NULL;
if (!poly || poly->exp < e) { nt->next = poly; return nt; }
while (curr && curr->exp > e) { prev = curr; curr = curr->next; }
if (curr && curr->exp == e) {

10
curr->coeff += c;
free(nt);
if (curr->coeff == 0) {
if (prev) prev->next = curr->next; else poly = curr->next;
free(curr);
}
} else {
if (prev) prev->next = nt; else poly = nt;
nt->next = curr;
}
return poly;
}

void displayPoly(struct Term* poly) {


if (!poly) { printf("0\n"); return; }
struct Term* t = poly;
while (t) {
if (t->coeff > 0 && t != poly) printf(" + ");
else if (t->coeff < 0) printf(" - ");
if (abs(t->coeff)!=1 || t->exp==0) printf("%d",abs(t->coeff));
if (t->exp > 0) printf("x");
if (t->exp > 1) printf("^%d", t->exp);
t = t->next;
} printf("\n");
}

int main() {
struct Term* p = NULL;
p = addTerm(p, 5, 3);
p = addTerm(p, -2, 2);
p = addTerm(p, 7, 1);
printf("Poly: "); displayPoly(p);
p = addTerm(p, 2, 2);
printf("Poly: "); displayPoly(p);
while(p){
struct Term* temp = p;
p = p->next;
free(temp);
}
return 0;
}

11
11. Stack Implementations (Array and Linked List)
11.1 Stack using Array
#include <stdio.h>
#define MAX_STACK 10

typedef struct { int items[MAX_STACK]; int top; } ArrayStack;

void initArrStack(ArrayStack* s) { s->top = -1; }


int isArrFull(ArrayStack* s) { return s->top == MAX_STACK - 1; }
int isArrEmpty(ArrayStack* s) { return s->top == -1; }

void pushArr(ArrayStack* s, int val) {


if (isArrFull(s)) { printf("Stack full.\n"); return; }
s->items[++(s->top)] = val;
}
int popArr(ArrayStack* s) {
if (isArrEmpty(s)) { printf("Stack empty.\n"); return -1; }
return s->items[(s->top)--];
}
void displayArrStack(ArrayStack* s) {
if(isArrEmpty(s)) {
printf("Stack is empty.\n");
return;
}
printf("Stack (top to bottom): ");
for (int i = s->top; i >= 0; i--) printf("%d ", s->items[i]);
printf("\n");
}

int main() {
ArrayStack s; initArrStack(&s);
pushArr(&s, 10); pushArr(&s, 20); pushArr(&s, 30);
displayArrStack(&s);
printf("Popped: %d\n", popArr(&s));
displayArrStack(&s);
return 0;
}

11.2 Stack using Linked List


#include <stdio.h>
#include <stdlib.h>

typedef struct SNode { int data; struct SNode* next; } SNode;


typedef struct { SNode* top; } LLStack;

12
void initLLStack(LLStack* s) { s->top = NULL; }
int isLLEmpty(LLStack* s) { return s->top == NULL; }

void pushLL(LLStack* s, int val) {


SNode* nn = (SNode*)malloc(sizeof(SNode));
nn->data = val; nn->next = s->top; s->top = nn;
}
int popLL(LLStack* s) {
if (isLLEmpty(s)) { printf("Stack empty.\n"); return -1; }
SNode* temp = s->top; int val = temp->data;
s->top = s->top->next; free(temp); return val;
}
void displayLLStack(LLStack* s) {
if(isLLEmpty(s)) {
printf("Stack is empty.\n");
return;
}
SNode* temp = s->top; printf("Stack (top to bottom): ");
while(temp) { printf("%d ", temp->data); temp = temp->next; }
printf("\n");
}

int main() {
LLStack s; initLLStack(&s);
pushLL(&s, 100); pushLL(&s, 200); pushLL(&s, 300);
displayLLStack(&s);
printf("Popped: %d\n", popLL(&s));
displayLLStack(&s);
while(!isLLEmpty(&s)) popLL(&s);
return 0;
}

12. Queue Implementation using Linked List


#include <stdio.h>
#include <stdlib.h>

typedef struct QNode { int data; struct QNode* next; } QNode;


typedef struct { QNode *front, *rear; } Queue;

Queue* createQueue() {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->front = q->rear = NULL; return q;
}
int isQEmpty(Queue* q) { return q->front == NULL; }

13
void enqueue(Queue* q, int val) {
QNode* nn = (QNode*)malloc(sizeof(QNode));
nn->data = val; nn->next = NULL;
if (q->rear == NULL) { q->front = q->rear = nn; return; }
q->rear->next = nn; q->rear = nn;
}
int dequeue(Queue* q) {
if (isQEmpty(q)) { printf("Queue empty.\n"); return -1; }
QNode* temp = q->front; int val = temp->data;
q->front = q->front->next;
if (q->front == NULL) q->rear = NULL;
free(temp); return val;
}
void displayQ(Queue* q) {
if(isQEmpty(q)) {
printf("Queue is empty.\n");
return;
}
QNode* temp = q->front; printf("Queue (front to rear): ");
while(temp) { printf("%d ", temp->data); temp = temp->next; }
printf("\n");
}

int main() {
Queue* q = createQueue();
enqueue(q, 1); enqueue(q, 2); enqueue(q, 3);
displayQ(q);
printf("Dequeued: %d\n", dequeue(q));
displayQ(q);
while(!isQEmpty(q)) {
dequeue(q);
}
free(q);
return 0;
}

13. Circular Queue Implementation using Linked List


#include <stdio.h>
#include <stdlib.h>

typedef struct CQNode { int data; struct CQNode* next; } CQNode;


typedef struct { CQNode* rear; } CQueue;

CQueue* createCQueue() {

14
CQueue* cq = (CQueue*)malloc(sizeof(CQueue));
cq->rear = NULL; return cq;
}
int isCQEmpty(CQueue* cq) { return cq->rear == NULL; }

void cqEnqueue(CQueue* cq, int val) {


CQNode* nn = (CQNode*)malloc(sizeof(CQNode)); nn->data = val;
if (isCQEmpty(cq)) { cq->rear = nn; cq->rear->next = cq->rear; }
else { nn->next = cq->rear->next; cq->rear->next = nn; cq->rear = nn; }
}
int cqDequeue(CQueue* cq) {
if (isCQEmpty(cq)) { printf("CQueue empty.\n"); return -1; }
CQNode* front = cq->rear->next; int val = front->data;
if (cq->rear == front) cq->rear = NULL;
else cq->rear->next = front->next;
free(front); return val;
}
void displayCQ(CQueue* cq) {
if (isCQEmpty(cq)) { printf("CQueue empty.\n"); return; }
CQNode* temp = cq->rear->next; printf("CQueue (front to rear): ");
do { printf("%d ", temp->data); temp = temp->next; } while (temp != cq->rear->next);
printf("\n");
}

int main() {
CQueue* cq = createCQueue();
cqEnqueue(cq, 10); cqEnqueue(cq, 20); cqEnqueue(cq, 30);
displayCQ(cq);
printf("Dequeued: %d\n", cqDequeue(cq));
displayCQ(cq);
while(!isCQEmpty(cq)) {
cqDequeue(cq);
}
free(cq);
return 0;
}

14. Binary Search Tree (Implement)


#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode { int data; struct TreeNode *left, *right; } TreeNode;

TreeNode* newTNode(int item) {


TreeNode* t = (TreeNode*)malloc(sizeof(TreeNode));

15
t->data = item; t->left = t->right = NULL; return t;
}
TreeNode* insertBST(TreeNode* node, int data) {
if (node == NULL) return newTNode(data);
if (data < node->data) {
node->left = insertBST(node->left, data);
} else if (data > node->data) {
node->right = insertBST(node->right, data);
}
return node;
}
void inorder(TreeNode* root) {
if (root) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
void freeBST(TreeNode* root) {
if (!root) return;
freeBST(root->left);
freeBST(root->right);
free(root);
}

int main() {
TreeNode* root = NULL;
root = insertBST(root, 50);
insertBST(root, 30);
insertBST(root, 20);
insertBST(root, 40);
insertBST(root, 70);
insertBST(root, 60);
insertBST(root, 80);
printf("Inorder of BST: "); inorder(root); printf("\n");
freeBST(root);
return 0;
}

15. Tree Traversal Operations


Demonstrates Inorder, Preorder, Postorder on a BST.
#include <stdio.h>
#include <stdlib.h>

16
typedef struct TreeNodeTrav {
int data;
struct TreeNodeTrav *left, *right;
} TreeNodeTrav;

TreeNodeTrav* newTNodeTrav(int item) {


TreeNodeTrav* t = (TreeNodeTrav*)malloc(sizeof(TreeNodeTrav));
t->data = item;
t->left = t->right = NULL;
return t;
}

TreeNodeTrav* insertBSTTrav(TreeNodeTrav* node, int data) {


if (node == NULL) {
return newTNodeTrav(data);
}
if (data < node->data) {
node->left = insertBSTTrav(node->left, data);
} else if (data > node->data) {
node->right = insertBSTTrav(node->right, data);
}
return node;
}

void freeBSTTrav(TreeNodeTrav* root) {


if (!root) {
return;
}
freeBSTTrav(root->left);
freeBSTTrav(root->right);
free(root);
}

void inorderTrav(TreeNodeTrav* root) {


if (root) {
inorderTrav(root->left);
printf("%d ", root->data);
inorderTrav(root->right);
}
}

void preorderTrav(TreeNodeTrav* root) {


if (root) {
printf("%d ", root->data);
preorderTrav(root->left);
preorderTrav(root->right);

17
}
}

void postorderTrav(TreeNodeTrav* root) {


if (root) {
postorderTrav(root->left);
postorderTrav(root->right);
printf("%d ", root->data);
}
}

int main() {
TreeNodeTrav* root = NULL;
root = insertBSTTrav(root, 50);
insertBSTTrav(root, 30);
insertBSTTrav(root, 70);
insertBSTTrav(root, 20);
insertBSTTrav(root, 40);
insertBSTTrav(root, 60);
insertBSTTrav(root, 80);

printf("Inorder: ");
inorderTrav(root);
printf("\n");

printf("Preorder: ");
preorderTrav(root);
printf("\n");

printf("Postorder: ");
postorderTrav(root);
printf("\n");

freeBSTTrav(root);
return 0;
}

16. Adjacency Matrix for a Given Graph


#include <stdio.h>
#define MAX_V 10

int adjMat[MAX_V][MAX_V];
int numV;

void initAdjMat(int n) {

18
numV = n;
for (int i = 0; i < numV; i++) {
for (int j = 0; j < numV; j++) {
adjMat[i][j] = 0;
}
}
}
void addEdgeMat(int u, int v) {
if (u<numV && v<numV) {
adjMat[u][v] = 1;
adjMat[v][u] = 1;
}
}
void displayAdjMat() {
printf("Adj Matrix:\n ");
for(int i=0; i<numV; i++) printf("%d ", i);
printf("\n");
for (int i = 0; i < numV; i++) {
printf("%d ", i);
for (int j = 0; j < numV; j++) {
printf("%d ", adjMat[i][j]);
}
printf("\n");
}
}

int main() {
initAdjMat(4);
addEdgeMat(0, 1);
addEdgeMat(0, 2);
addEdgeMat(1, 2);
addEdgeMat(2, 3);
displayAdjMat();
return 0;
}

17. BFS and DFS Traversal


Uses adjacency matrix.
#include <stdio.h>
#define MAX_VT 10

int adjM[MAX_VT][MAX_VT];
int nV;
int visited[MAX_VT];

19
int bfs_q[MAX_VT], front_q = -1, rear_q = -1;
void enq(int item) {
if(rear_q == MAX_VT-1) return;
if(front_q == -1) front_q=0;
rear_q++;
bfs_q[rear_q]=item;
}
int deq() {
if(front_q == -1 || front_q > rear_q) return -1;
int item = bfs_q[front_q++];
if(front_q > rear_q) front_q=rear_q=-1;
return item;
}
int is_q_empty() { return front_q == -1; }

void initGraphTrav(int n) {
nV = n;
for(int i=0; i<nV; i++) {
visited[i]=0;
for(int j=0; j<nV; j++) adjM[i][j]=0;
}
front_q = rear_q = -1;
}
void addEdgeTrav(int u, int v) {
if(u<nV && v<nV) {
adjM[u][v]=1;
adjM[v][u]=1;
}
}

void DFS(int v) {
printf("%d ", v);
visited[v] = 1;
for (int i = 0; i < nV; i++) {
if (adjM[v][i] && !visited[i]) {
DFS(i);
}
}
}

void BFS(int startV) {


for(int i=0; i<nV; i++) visited[i]=0;
front_q = rear_q = -1;
visited[startV] = 1;
enq(startV);

20
while(!is_q_empty()) {
int curr = deq();
printf("%d ", curr);
for(int i=0; i<nV; i++) {
if(adjM[curr][i] && !visited[i]) {
visited[i]=1;
enq(i);
}
}
}
}

int main() {
initGraphTrav(5);
addEdgeTrav(0,1);
addEdgeTrav(0,2);
addEdgeTrav(1,3);
addEdgeTrav(1,4);
addEdgeTrav(2,4);

printf("DFS (start 0): "); DFS(0); printf("\n");


printf("BFS (start 0): "); BFS(0); printf("\n");
return 0;
}

21

You might also like