0% found this document useful (0 votes)
33 views33 pages

DSA Lab File

Uploaded by

hs8491795
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)
33 views33 pages

DSA Lab File

Uploaded by

hs8491795
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/ 33

SRI SUKHMANI INSTITUTE

OF
ENGINEERING & TECHNOLOGY

Lab file
Of
“Data Structure & Algorithm “
Branch: - Computer Science & Engineering (3rd Sem)
Course code: - BTCS 303-18

Submitted to: - Mr. GURKIRAT SINGH


Submitted by: - JYOTISMITA DAS
Roll no: - 2306156

Teacher’s sign

1
Serial Contents Date of
No submission
1 Write a program to insert a new element at the end as well
as at a given position in an array.
2 Write a program to delete an element from a given whose
value is given or whose position is given.
3 Write a program to find the location of a given element
using Linear Search.
4 Write a program to find the location of a given element
using Binary Search.
5 Write a program to implement push and pop operations on
a stack using linear array.
6 Write a program to convert an infix expression to a postfix
expression using stacks.
7 Write a program to evaluate a postfix expression using
stacks.
8 Write a recursive function for Tower of Hanoi problem.
9 Write a program to implement insertion and deletion
operations in a queue using linear array.
10 Write a menu driven program to perform following
insertion operations in a single linked list:
Insertion at beginning
Insertion at end
Insertion after a given node
Traversing a linked list
11 Write a program to implement push and pop operations on
a stack using linked list.
12 Write a program to implement push and pop operations on
a queue using linked list.
13 Program to sort an array of integers in ascending order
using bubble sort.
14 Program to sort an array of integers in ascending order
using selection sort.
15 Program to sort an array of integers in ascending order
using insertion sort.
16 Program to sort an array of integers in ascending order
using quick sort
17 Program to traverse a Binary search tree in Pre-order, In-
order and Post - order.
18 Program to traverse graphs using BFS.
19 Program to traverse graphs using DFS.
2
1. Write a program to insert a new element at the end as well as at a given position in
an array.

#include<iostream>
using namespace std;
void insertAtEnd(int arr[],int &n,int element,int maxSize){
if(n>=maxSize){
cout<<"Array is full,can'tinsert at the end"<<endl;
return;
}
arr[n]=element;
n++;
}

void insertAtPosition(int arr[],int &n,int element,int position,int maxSize){


if(position<0||position>n||n>=maxSize){
cout<<"Invalid position or array is full"<<endl;
return;
}
for(int i=n;i>position;i--){
arr[i]=arr[i-1];
}
arr[position]=element;
n++;
}
int main(){
const int maxSize=10;
int arr[maxSize]={1,2,3,4,5};
int n=5;
int newElement=6;
insertAtEnd(arr ,n ,newElement,maxSize);
cout<<"Array after inserting at end :";
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
int element=10;
int position=2;
insertAtPosition(arr,n,element,position,maxSize);
cout<<"Array after inserting at position"<<position<<":";
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}

Output:
Array after inserting at end :1 2 3 4 5 6
Array after inserting at position2:1 2 10 3 4 5 6
3
2. Write a program to delete an element from a given whose value is given or whose
position is given.

#include<iostream>
using namespace std;
void deleteByValue(int arr[],int &size,int value){
int pos=-1;
for(int i=0;i<size;i++){
if(arr[i]==value){
pos=i;
break;
}
}
if(pos==-1){
cout<<"Value not found in the array"<<endl;
return;
}
for(int i=pos;i<size-1;i++){
arr[i]=arr[i+1];
}
size--;
cout<<"Value deleted from the array"<<endl;
}

void deleteByPosition(int arr[],int &size,int pos){


if(pos<0||pos>=size){
cout<<"Invalid position!"<<endl;
return;
}
for(int i=pos;i<size-1;i++){
arr[i]=arr[i+1];
}
size--;
cout<<"Element at position "<<pos<<" deleted"<<endl;
}

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


for(int i=0;i<size;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}

int main(){
int arr[]={10,20,30,40,50};
int size=5;
cout<<"Original array :";
displayArray(arr,size);
int valueToDelete=30;
deleteByValue(arr,size,valueToDelete);
4
cout<<"Array after deleting value "<<valueToDelete<<" : ";
displayArray(arr,size);
int positionToDelete=2;
deleteByPosition(arr,size,positionToDelete);
cout<<"Array after deleting position "<<positionToDelete<<" : ";
displayArray(arr,size);
return 0;
}

Output:
Original array :10 20 30 40 50
Value deleted from the array
Array after deleting value 30 : 10 20 40 50
Element at position 2 deleted
Array after deleting position 2 : 10 20 50

5
3. Write a program to find the location of a given element using Linear Search.

#include<iostream>
using namespace std;
int linearSearch(int arr[],int size,int target){
for(int i=0;i<size;i++){
if(arr[i]==target){
return i;
}
}
return-1;
}
int main(){
int arr[]={10,25,30,45,50};
int target=30;
int size=sizeof(arr)/sizeof(arr[0]);
int result=linearSearch(arr,size,target);
if(result!=-1){
cout<<"Element "<<target<<" found at index "<<result<<endl;
}
else{
cout<<"Element "<<target<<" not found in the array"<<endl;
}
return 0;
}

Output:
Element 30 found at index 2

6
4. Write a program to find the location of a given element using Binary Search.

#include<iostream>
using namespace std;
int binarySearch(int arr[],int size,int target){
int left=0;
int right=size-1;
while(left<=right){
int mid=left+(right-left)/2;
if(arr[mid]==target){
return mid;
}
if(arr[mid]<target){
left=mid+1;
}
else{
right=mid-1;
}
}
return-1;
}
int main(){
int arr[]={10,20,30,40,50};
int target=30;
int size=sizeof(arr)/sizeof(arr[0]);
int result=binarySearch(arr,size,target);
if(result!=-1){
cout<<"Element "<<target<<" found at index "<<result<<endl;
}
else{
cout<<"Element "<<target<<" not found in the array"<<endl;
}
return 0;
}

Output:
Element 30 found at index 2

7
5. Write a program to implement push and pop operations on a stack using linear
array.

#include<iostream>
using namespace std;
const int MAX_SIZE=5;
class Stack{
private:
int arr[MAX_SIZE];
int top;
public:
Stack():top(-1){

}
void push(int value){
if(top>=MAX_SIZE-1){
cout<<"Stack Overflow!can't push"<<value<<endl;
}
else{
top++;
arr[top]=value;
cout<<value<<" pushed onto stack "<<endl;
}
}
void pop(){
if(top<0){
cout<<"stack Underflow! can't pop element"<<endl;
}
else{
cout<<arr[top]<<" popped from stack"<<endl;
top--;
}
}
void display(){
if(top<0){
cout<<"Stack is empty"<<endl;
}
else{
cout<<"Stack elements ";
for(int i=0;i<=top;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
}
};
int main(){
Stack stack;
stack.push(10);
stack.push(20);
8
stack.push(30);
stack.display();
stack.pop();
stack.display();
stack.push(40);
stack.push(50);
stack.push(60);
stack.display();
return 0;
}

Output:
10 pushed onto stack
20 pushed onto stack
30 pushed onto stack
Stack elements 10 20 30
30 popped from stack
Stack elements 10 20
40 pushed onto stack
50 pushed onto stack
60 pushed onto stack
Stack elements 10 20 40 50 60

9
6. Write a program to convert an infix expression to a postfix expression using stacks.

#include<iostream>
#include<stack>
#include<string>
using namespace std;
int precedence(char op){
if(op=='+'||op=='-'){
return 1;
}
else if(op=='*'||op=='/'){
return 2;
}
return 0;
}
bool isOperator(char c){
return(c=='+'||c=='*'||c=='/');
}
string infixToPostfix(const string & infix){
stack<char>s;
string postfix;
for(char c:infix){
if(isalnum(c)){
postfix+=c;
}
else if(c=='('){
s.push(c);
}
else if(c==')'){
while(!s.empty()&&s.top()!='('){
postfix+=s.top();
s.pop();
}
s.pop();
}
else if(isOperator(c)){
while(!s.empty()&&precedence(s.top())>=precedence(c)){
postfix+=s.top();
s.pop();
}
s.push(c);
}
}
while(!s.empty()){
postfix+=s.top();
s.pop();
}
return postfix;
}
int main(){
10
string infix;
cout<<"Enter an infix expression : "<<endl;
cin>>infix;
string postfix=infixToPostfix(infix);
cout<<"Postfix expression : "<<postfix<<endl;
return 0;
}

Output:
Enter an infix expression :
(A+B)*C
Postfix expression : AB+C*

11
7. Write a program to evaluate a postfix expression using stacks.

#include <iostream>
#include <stack>
#include <sstream>

using namespace std;


int evaluatePostfix(const string& expression) {
stack<int> s;
istringstream iss(expression);
string token;
while (iss >> token) {
if (isdigit(token[0])) {
s.push(stoi(token));
} else {
int right = s.top(); s.pop();
int left = s.top(); s.pop();
int result;

switch (token[0]) {
case '+':
result = left + right;
break;
case '-':
result = left - right;
break;
case '*':
result = left * right;
break;
case '/':
result = left / right;
break;
default:
cout << "Error: Unknown operator " << token << endl;
return 0;
}
s.push(result);
}
}

return s.top();
}

int main() {
string postfixExpression;

cout << "Enter a postfix expression (e.g., 3 4 + 2 *): ";


getline(cin, postfixExpression);

int result = evaluatePostfix(postfixExpression);


12
cout << "The result of the postfix expression is: " << result << endl;

return 0;
}

Output:
Enter a postfix expression (e.g., 3 4 + 2 *): 76*65+
The result of the postfix expression is: 76

13
8. Write a recursive function for Tower of Hanoi problem.

#include <iostream>
using namespace std;
void towerOfHanoi(int n, char source, char target, char auxiliary) {
if (n == 1) {
cout << "Move disk 1 from " << source << " to " << target << endl;
return;
}
towerOfHanoi(n - 1, source, auxiliary, target);
cout << "Move disk " << n << " from " << source << " to " << target << endl;
towerOfHanoi(n - 1, auxiliary, target, source);
}

int main() {
int n;
cout << "Enter the number of disks: ";
cin >> n;

towerOfHanoi(n, 'A', 'C', 'B');

return 0;
}

Output:
Enter the number of disks: 4
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Move disk 3 from A to B
Move disk 1 from C to A
Move disk 2 from C to B
Move disk 1 from A to B
Move disk 4 from A to C
Move disk 1 from B to C
Move disk 2 from B to A
Move disk 1 from C to A
Move disk 3 from B to C
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C

14
9. Write a program to implement insertion and deletion operations in a queue using
linear array.

#include <iostream>
#define MAX 100

using namespace std;

class Queue {
private:
int items[MAX];
int front, rear;

public:
Queue() {
front = -1;
rear = -1;
}

bool isFull() {
return (rear == MAX - 1);
}

bool isEmpty() {
return (front == -1 || front > rear);
}

void enqueue(int element) {


if (isFull()) {
cout << "Queue is full! Cannot enqueue " << element << endl;
return;
}
if (front == -1) {
front = 0;
}
rear++;
items[rear] = element;
cout << "Enqueued: " << element << endl;
}

int dequeue() {
if (isEmpty()) {
cout << "Queue is empty! Cannot dequeue." << endl;
return -1;
}
int dequeuedElement = items[front];
front++;
cout << "Dequeued: " << dequeuedElement << endl;
return dequeuedElement;
}
15
void display() {
if (isEmpty()) {
cout << "Queue is empty!" << endl;
return;
}
cout << "Queue elements: ";
for (int i = front; i <= rear; i++) {
cout << items[i] << " ";
}
cout << endl;
}
};

int main() {
Queue q;
int choice, value;

do {
cout << "\nQueue Operations Menu:\n";
cout << "1. Enqueue\n";
cout << "2. Dequeue\n";
cout << "3. Display\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter the value to enqueue: ";
cin >> value;
q.enqueue(value);
break;
case 2:
q.dequeue();
break;
case 3:
q.display();
break;
case 4:
cout << "Exiting the program." << endl;
break;
default:
cout << "Invalid choice! Please enter again." << endl;
}
} while (choice != 4);

return 0;
}

16
Output:
Queue Operations Menu:
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter the value to enqueue: 23
Enqueued: 23

Queue Operations Menu:


1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter the value to enqueue: 234
Enqueued: 234

Queue Operations Menu:


1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 3
Queue elements: 23 234

17
10.Write a menu driven program to perform following insertion operations in a single
linked list:

i. Insertion at beginning
ii. Insertion at end
iii. Insertion after a given node
iv. Traversing a linked list

#include <iostream>
using namespace std;

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

class LinkedList {
private:
Node* head;

public:
LinkedList() {
head = nullptr;
}

void insertAtBeginning(int value) {


Node* newNode = new Node();
newNode->data = value;
newNode->next = head;
head = newNode;
}

void insertAtEnd(int value) {


Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;

if (head == nullptr) {
head = newNode;
return;
}

Node* temp = head;


while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}

18
void insertAfter(int afterValue, int value) {
Node* temp = head;
while (temp != nullptr && temp->data != afterValue) {
temp = temp->next;
}

if (temp == nullptr) {
cout << "Node with value " << afterValue << " not found." << endl;
return;
}

Node* newNode = new Node();


newNode->data = value;
newNode->next = temp->next;
temp->next = newNode;
}

void traverse() {
Node* temp = head;
if (temp == nullptr) {
cout << "The list is empty." << endl;
return;
}

while (temp != nullptr) {


cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};

int main() {
LinkedList list;
int choice, value, afterValue;

do {
cout << "\nMenu:\n";
cout << "1. Insertion at Beginning\n";
cout << "2. Insertion at End\n";
cout << "3. Insertion after a given node\n";
cout << "4. Traverse the linked list\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter value to insert at beginning: ";
cin >> value;

19
list.insertAtBeginning(value);
break;
case 2:
cout << "Enter value to insert at end: ";
cin >> value;
list.insertAtEnd(value);
break;
case 3:
cout << "Enter value to insert after: ";
cin >> afterValue;
cout << "Enter value to insert: ";
cin >> value;
list.insertAfter(afterValue, value);
break;
case 4:
cout << "Linked list: ";
list.traverse();
break;
case 5:
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != 5);

return 0;
}

Output:
Menu:
1. Insertion at Beginning
2. Insertion at End
3. Insertion after a given node
4. Traverse the linked list
5. Exit
Enter your choice: 1
Enter value to insert at beginning: 56 87 96
Enter your choice: 2
Enter value to insert at end: 35
Enter your choice: 4
Linked list: 96 87 56 35

20
11.Write a program to implement push and pop operations on a stack using linked list.

#include <iostream>
using namespace std;

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

class Stack {
private:
Node* top;

public:
Stack() {
top = nullptr;
}

void push(int value) {


Node* newNode = new Node();
newNode->data = value;
newNode->next = top;
top = newNode;
}

void pop() {
if (top == nullptr) {
cout << "Stack is empty." << endl;
return;
}
Node* temp = top;
top = top->next;
delete temp;
}

void display() {
Node* temp = top;
if (temp == nullptr) {
cout << "Stack is empty." << endl;
return;
}
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};

21
int main() {
Stack s;
s.push(10);
s.push(20);
s.push(30);

cout << "Stack after pushing elements: ";


s.display();

s.pop();
cout << "Stack after popping an element: ";
s.display();

return 0;
}

Output:
Stack after pushing elements: 30 20 10
Stack after popping an element: 20 10

22
12.Write a program to implement push and pop operations on a queue using linked
list.

#include <iostream>
using namespace std;

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

class Queue {
private:
Node* front;
Node* rear;

public:
Queue() {
front = nullptr;
rear = nullptr;
}

void push(int value) {


Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (rear == nullptr) {
front = rear = newNode;
return;
}
rear->next = newNode;
rear = newNode;
}

void pop() {
if (front == nullptr) {
cout << "Queue is empty." << endl;
return;
}
Node* temp = front;
front = front->next;
if (front == nullptr) {
rear = nullptr;
}
delete temp;
}

void display() {
Node* temp = front;
if (temp == nullptr) {
23
cout << "Queue is empty." << endl;
return;
}
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};

int main() {
Queue q;
q.push(10);
q.push(20);
q.push(30);

cout << "Queue after pushing elements: ";


q.display();

q.pop();
cout << "Queue after popping an element: ";
q.display();

return 0;
}

Output:
Queue after pushing elements: 10 20 30
Queue after popping an element: 20 30

24
13.Program to sort an array of integers in ascending order using bubble sort.

#include <iostream>
using namespace std;

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 n) {


for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Original array: ";


printArray(arr, n);

bubbleSort(arr, n);

cout << "Sorted array: ";


printArray(arr, n);

return 0;
}

Output:
Original array: 64 34 25 12 22 11 90
Sorted array: 11 12 22 25 34 64 90

25
14.Program to sort an array of integers in ascending order using selection sort.

#include <iostream>
using namespace std;

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


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

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


for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Original array: ";


printArray(arr, n);

selectionSort(arr, n);

cout << "Sorted array: ";


printArray(arr, n);

return 0;
}

Output:
Original array: 64 25 12 22 11
Sorted array: 11 12 22 25 64

26
15.Program to sort an array of integers in ascending order using insertion sort.

#include <iostream>
using namespace std;

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


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

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


for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}

int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Original array: ";


printArray(arr, n);

insertionSort(arr, n);

cout << "Sorted array: ";


printArray(arr, n);

return 0;
}

Output:
Original array: 12 11 13 5 6
Sorted array: 5 6 11 12 13

27
16.Program to sort an array of integers in ascending order using quick sort.

#include <iostream>
using namespace std;

int partition(int arr[], int low, int high) {


int pivot = arr[high];
int i = low - 1;

for (int j = low; j < high; j++) {


if (arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

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


for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Original array: ";


printArray(arr, n);

quickSort(arr, 0, n - 1);

cout << "Sorted array: ";


printArray(arr, n);

return 0;
}
Output:
Original array: 10 7 8 9 1 5
Sorted array: 1 5 7 8 9 10
28
17.Program to traverse a Binary search tree in Pre-order , In-order and Post-order.

#include <iostream>
using namespace std;

struct Node {
int data;
Node* left;
Node* right;
Node(int value) : data(value), left(nullptr), right(nullptr) {}
};

class BST {
private:
Node* root;

Node* insert(Node* node, int value) {


if (!node) return new Node(value);
if (value < node->data) node->left = insert(node->left, value);
else node->right = insert(node->right, value);
return node;
}

void preOrder(Node* node) {


if (node) {
cout << node->data << " ";
preOrder(node->left);
preOrder(node->right);
}
}

void inOrder(Node* node) {


if (node) {
inOrder(node->left);
cout << node->data << " ";
inOrder(node->right);
}
}

void postOrder(Node* node) {


if (node) {
postOrder(node->left);
postOrder(node->right);
cout << node->data << " ";
}
}

public:
BST() : root(nullptr) {}

29
void insert(int value) {
root = insert(root, value);
}

void traverse() {
cout << "Pre-order: "; preOrder(root); cout << endl;
cout << "In-order: "; inOrder(root); cout << endl;
cout << "Post-order: "; postOrder(root); cout << endl;
}
};

int main() {
BST tree;
int value;
cout << "Enter values (end with -1): ";
while (cin >> value && value != -1) {
tree.insert(value);
}
tree.traverse();
return 0;
}

Output:
Enter values (end with -1): 8
7
6
12
32
14
-1
Pre-order: 8 7 6 12 32 14
In-order: 6 7 8 12 14 32
Post-order: 6 7 14 32 12 8

30
18.Program to traverse graphs using BFS.

#include <iostream>
#include <queue>
using namespace std;

#define MAX_VERTICES 100

class Graph {
private:
int adj[MAX_VERTICES][MAX_VERTICES];
int vertices;
public:
Graph(int v) {
vertices = v;
for (int i = 0; i < MAX_VERTICES; i++) {
for (int j = 0; j < MAX_VERTICES; j++) {
adj[i][j] = 0;
}
}
}

void addEdge(int u, int v) {


adj[u][v] = 1;
adj[v][u] = 1;
}

void BFS(int start) {


bool visited[MAX_VERTICES] = {false};
queue<int> q;

visited[start] = true;
q.push(start);

cout << "BFS Traversal starting from vertex " << start << ": ";

while (!q.empty()) {
int current = q.front();
q.pop();

cout << current << " ";

for (int i = 0; i < vertices; i++) {


if (adj[current][i] == 1 && !visited[i]) {
visited[i] = true;
q.push(i);
}
}
}
cout << endl;
31
}
};

int main() {
int vertices, edges;
cout << "Enter number of vertices: ";
cin >> vertices;
cout << "Enter number of edges: ";
cin >> edges;

Graph g(vertices);

cout << "Enter the edges (u v): " << endl;


for (int i = 0; i < edges; i++) {
int u, v;
cin >> u >> v;
g.addEdge(u, v);
}

int startVertex;
cout << "Enter the starting vertex for BFS: ";
cin >> startVertex;

g.BFS(startVertex);

return 0;
}

Output:
Enter number of vertices: 6
Enter number of edges: 5
Enter the edges (u v):
8
2
6
5
4
3
2
4
78
98
Enter the starting vertex for BFS: 2
BFS Traversal starting from vertex 2: 2 4 3

32
19.Program to traverse graphs using DFS.

#include<iostream>
using namespace std;
const int MAX_NODES=5;
void DFS(int node,int adj[MAX_NODES][MAX_NODES],bool visited[MAX_NODES]){
visited[node]=true;
cout<<node<<" ";
for(int i=0;i<MAX_NODES;i++){
if(adj[node][i]){
DFS(i,adj,visited);
}
}
}

int main(){
int adj[MAX_NODES][MAX_NODES]={0,1,1,0,0};
bool visited[MAX_NODES]={false};
cout<<"DFS traversal starting from node 0 :";
DFS(0,adj,visited);
cout<<endl;
return 0;
}

Output:
DFS traversal starting from node 0 :0 1 2

33

You might also like