Name: Harsh Dugar
UID : 2022200034
Class EXTC TY
Experiment No. 6-B
AIM:
Implement Breadth First Search (ODD UID No.)and Depth First
Search (EVEN UID No.) Traversal for given Graph. Graph should be
dynamic , means it should accept number of vertices and edges ,
dynamically.
Program 1
THEORY: In this experiment we learnt continued learning Graphs, graphs are a
complex data strucure that shine in capturing interrelations between
vertices. Just like linked lists and trees, they have nodes that are
connected to each other by edges. We implement our graph using an
adjacency matrix, we take in the number of vertices from the user as
n. We then create a n*n matrix initialized with 0 at all places
signifying no edge. We then run a for loop whose iterations run across
the vertices. We ask the user for the number of edges at the current
vertex.
My task was to implement DFS traversal and search in this Lab. The
dfs traversal needed to also print the start and end instances of every
push and pop and the printing of all pushes and pops, along with the
traversal.
My first instict was to implement dfs using recursion which I did but
it cannot print that. So I implemented it using a stack and an array to
mark visited and a loop that runs until the stack ran empty. For this,
we first push the root element into the stack. Then for every iteration
we extract the top of the stack and mark it as visited and process the
current Vertex.
Then we run a loop for the current Vertex across its adjacency matrix
and if we find an unvisited vertex, we push it into the stack and
continue. When the current vertex has no unvisited children, we pop
the top element of the stack. While all of this is happening, we use a
variable to keep track of time and update the start and end arrays for
our vertices as they pass by.
We implement dfs search similarly using the same logic, just
changing the printing of traversal, to comparison with the target node.
At the end our function, print the vertices being pushed into and
popped from the dfs stack, the start time and end time array, the dfs
traversal and whether the given vertex is present in the graph or not.
ALGORITHM:
1) Implement DFS Traversal
1. Initialize:
• A visited array of size n, initialized to 0.
• A stack to track DFS traversal.
• A start array to store discovery times.
• An end array to store finishing times.
• A timer initialized to 1.
2. Push the starting vertex onto the stack and mark it as
visited.
3. While the stack is not empty:
• Peek the top element of the stack.
• If the node has not been assigned a start time,
update it.
• Check for unvisited adjacent nodes in the adjacency
matrix.
• If found, push it onto the stack, mark it as
visited, and continue.
• If no unvisited adjacent node is found, pop the stack
and update the end time.
4. Print the push/pop operations, start and end times, and
DFS traversal order.
2) Implement DFS Search (Using Stack)
1. Initialize:
• A visited array of size n, initialized to 0.
• A stack and push the starting node onto it.
2. While the stack is not empty:
• Pop the top element.
• If it matches the target, return true.
• Otherwise, mark it as visited and push all unvisited
adjacent nodes.
3. If the search completes without finding the target, return
false.
4. Print whether the target node is found or not.
CODE: #include<iostream>
#include<stack>
using namespace std;
int n;
class Node{
public:
int val = -1;
Node* next = NULL;
Node(int _val){
val = _val;
}
};
void listTraversal(Node* root){
Node* curr = root;
if(curr->val == -1){ return; }
while(curr != NULL){
cout << curr->val << " ";
curr = curr->next;
}
}
void dfsTraversal(int n, int arr[][100], int root){
int vis[n] = {0};
stack<int> st;
int timer = 1;
int start[n] = {0};
int end[n] = {0};
int trav[n];
int travCnt = 0;
st.push(root);
cout<<"Pushing : "<<root<<endl;
vis[root - 1] = 1;
while(!st.empty()){
int curr = st.top();
if (start[curr - 1] == 0) {
start[curr - 1] = timer++;
trav[travCnt++] = curr;
}
bool hasUnvisited = false;
for(int i = 0; i < n; i++){
if(arr[curr - 1][i] == 1 && vis[i] == 0){
st.push(i + 1);
cout<<"Pushing : "<<i+1<<endl;
vis[i] = 1;
hasUnvisited = true;
break;
}
}
if (!hasUnvisited) {
int ctop = st.top();
cout<<"Popping : "<<ctop<<endl;
st.pop();
if (end[curr - 1] == 0) {
end[curr - 1] = timer++;
}
}
}
cout << "Start timer : ";
for(int i = 0; i < n; i++){ cout << start[i] << " "; }
cout << endl << "End Timer : ";
for(int i = 0; i < n; i++){ cout << end[i] << " "; }
cout << endl << "DFS Traversal : ";
for(int i = 0; i < n; i++){ cout << trav[i] << " "; }
cout << endl;
}
bool dfs(int n, int arr[][100], int vis[], int tgt, int curr){
stack<int> st;
st.push(curr);
while(!st.empty()){
int curr = st.top();
st.pop();
if (curr == tgt) {
return true;
}
vis[curr - 1] = 1;
for(int i = 0; i < n; i++){
if(arr[curr - 1][i] == 1 && vis[i] == 0){
st.push(i + 1);
}
}
}
return false;
}
int main(){
cout << "Enter the number of vertices of the graph : ";
cin >> n;
int vis[n];
int arr[100][100] = {0};
int edges[n];
for(int i = 0; i < n; i++){
edges[i] = 0;
for(int j = 0; j < n; j++){ arr[i][j] = 0; }
}
for(int i = 0; i < n; i++){
cout << "Vertex " << i + 1 << " , enter the number of edges : ";
cin >> edges[i];
cout << "Enter the edges : ";
for(int j = 0; j < edges[i]; j++){
int curr;
cin >> curr;
if(curr == i + 1){ curr = -1; }
arr[i][curr - 1] = 1;
}
cout << endl;
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(arr[i][j] == -1){ cout << "0 "; }
else{ cout << arr[i][j] << " "; }
}
cout << endl;
}
cout << "Starting DFS Traversal : " << endl;
dfsTraversal(n, arr, 1);
while(true){
int curr;
cout << "Enter the element you wish to search for (or enter -1 to
leave) : ";
cin >> curr;
if(curr == -1) break;
for(int i = 0; i < n; i++){ vis[i] = 0; }
bool pres = dfs(n, arr, vis, curr, 1);
if(pres){ cout << "The searched node is present" << endl; }
else{ cout << "The searched node is not present" << endl; }
}
return 0;
}
OUTPUT:
CONCLUSION: In this experiment, we successfully implemented Depth First Search
traversal and search using an Adjacency Matrix representation of a
graph. The DFS algorithm allows us to explore a graph deeply by
visiting a node and then recursively visiting all its adjacent unvisited
nodes before backtracking. The iterative stack-based implementation
of DFS provided a clear way to track the traversal process, ensuring
that we could observe the start and end times of each vertex. We used
this to calculated all the variables assigned to us such as start and end
times and search whether the given elemment is present.