DSC Answer Bank
DSC Answer Bank
1. Explain ADT with an example. Explain the Concept of Linear and Non-Linear Data Structures.
2. Define Function. Describe the types of Functions with suitable ‘C’ Programs and Output.
Ans) Function
In c, we can divide a large program into the basic building blocks known as function. The function
contains the set of programming statements enclosed by {}. A function can be called multiple times to
provide reusability and modularity to the C program.
Types of Functions
There are two types of functions in C programming:
Library Functions: are the functions which are declared in the C header files such as scanf(), printf(),
gets(), puts(), ceil(), floor() etc.
User-defined functions: are the functions which are created by the C programmer, so that he/she can use it
many times. It reduces the complexity of a big program and optimizes the code.
3. Draw the structure of ‘C’ Program and discuss the same with simple ‘C’ Program.
● Preprocessor Commands
● Functions
● Variables
● Statements & Expressions
● Comments
#include <stdio.h>
int main(){
/* my first program in C */
printf("Hello, World!");
return 0;
}
Ans)
5. Define String. Show any five String operations with suitable ‘C’ Code.
Ans)
String in C programming is a sequence of characters terminated with a null character ‘\0’.
Strings are defined as an array of characters. The difference between a character array and a
string is the string is terminated with a unique character ‘\0’.
Both of these functions are defined in string.h file. Let’s see one example of these functions:
#include main()
Int main()
{
char temp[20];
printf(“Enter your Name”);
gets(temp);
printf(“My Name is: ”);
puts(temp);
return 0;
}
2) strcat()
For the cases when one string has to be appended at the end of another string, this function is being used.
Function strcat can append a copy of the source string at the end of the destination string. The strcat() is
one of the string operations in c which concatenates two strings, meaning it joins the character strings
end-to-end. In the strcat() operation, the destination string’s null character will be overwritten by the
source string’s first character, and the previous null character would now be added at the end of the new
destination string which is a result of stcrat() operation.
The user has to pass two arguments that are described below:
● src
● dest
Here at the place of “src” string is specified, while at the place of ‘dest’ the destination string in which we
have to append the source string is specified.
Example:
#include<string.h>
int main()
{
char src[20]= “ before”;
char dest[20]= “after ”;
strcat(dest, src);
puts(dest);
return 0;
}
3) Function strlen()
One more function of string header file that can be directly used for the strings is strlen(). You can use the
function strlen(), the string function in C, when you have to find out the length of any string. The strlen()
string functions in c basically calculate the length of a given string. However, one can also write a
program manually to find out the length of any string, but the use of this direct function can save your
time and the example is given below:
#include<stdio.h>
int main()
{
int length;
char s[20] = “We are Here”;
length=strlen(s);
printf(“\Length of the string is = %d \n”, length);
return 0;
}
4) Function strcpy()
If you have to copy the content of one string to another string, then this function is being used. Even the
null characters are copied in the process. Syntax of the function is strcpy(dest,source). The function can
copy the content of one string to another. One example of the function is given below:
#include<string.h>
int main()
{
char src[20]= “ Destination”;
char dest[20]= “”;
printf(“\n source string is = %s”, src);
printf(“\n destination string is = %s”, dest);
strcpy(dest, src);
printf (“\ntarget string after strcpy() = %s”, dest);
return 0;
}
Output:
5) Function strcmp()
To compare two strings to know whether they are same or not we can use strcmp() function.This string
functions in c, compares two strings. While comparing the strings takes two parameters into account
namely –
str1
str2
On comparing the return value be determined basis the strings setup as shown below.
The function returns a definite value that may be either 0, >0, or <0. In this function, the two values
passed are treated as case sensitive means ‘A’ and ‘a’ are treated as different letters. The values returned
by the function are used as:
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]=”copy”;
char str2[]=”Trophy”;
int I,j,k;
i=strcmp(str1, “copy”);
j=strcmp(str1, str2);
k-strcmp(str1, “f”);
printf(“\n %d %d %d”,I,j,k);
return 0;
}
Output: 0 -1 1
Module 2
1. Write an algorithm to convert infix to postfix expression and explain the same for any given
expression.
Ans)
Algorithm:
Step1: Start the Program
Step2: Include the necessary header files
Step3: Declare the functions with the prototypes
Step4: Declare the Variables
Step 5: Get the valid infix expression using scanf() function
Step 6: Call the function evaluate() and start scanning the input tokens one by one.
Step 7: If the scanned token is an operator then perform the following operations:
● If the symbol is ‘(‘ then push it onto stack
● If the symbol is ‘)’ then pop the operators from ‘(‘ to ‘)’ and push it to postfix expression
● If the symbol is ‘+’ or ‘-‘ or ‘*’ or ’/’ or ‘%’ or ‘^’ or ‘$’ then check the precedence of the
operator with the operator in stack.
● If the stack operator is of higher precedence / equal precedence than the incoming operator, then
pop the stack operator to postfix expression and then the incoming operator to stack.
● Else push the operator onto stack.
Step 8: If the scanned token is an operand then push into postfix expression
Step 9: Continue the steps 7 & 8 until the input token becomes empty
Step 10: Print the Postfix expression
Step 11: Stop the Program execution
Example:
A*(B+C)*D
Symbol Stack Output
A empty A
* + A
( *( A
B *( AB
+ *(+ AB
C *(+ ABC
) * ABC+
* * ABC+*
D empty ABC+*D*
2. Write a Program in ‘C’ to implement stack data structure with its associated operations.
Ans) A menu driven Program in C for the following operations on STACK of Integers (Array
Implementation of Stack with maximum size MAX)
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
int s[5],top=-1;
void push()
{
if(top==4)
printf("\nStack overflow!!!!");
else
{
printf("\nEnter element to insert:");
scanf("%d",&s[++top]);
}
}
void pop()
{
if(top==-1)
printf("\nStack underflow!!!");
else
printf("\nElement popped is: %d",s[top--]);
}
void disp()
{
int t=top;
if(t==-1)
printf("\nStack empty!!");
else
printf("\nStack elements are:\n");
while(t>=0)
printf("%d ",s[t--]);
}
void pali()
{
int num[5],rev[5],i,t;
for(i=0,t=top;t>=0;i++,t--)
num[i]=rev[t]=s[t];
for(i=0;i<=top;i++)
if(num[i]!=rev[i])
break;
if(i==top+1)
printf("\nIt is a palindrome");
else
printf("\nIt is not a palindrome");
}
int main()
{
int ch;
do
{
printf("\n...Stack operations.....\n");
printf("1.PUSH\n");
printf("2.POP\n");
printf("3.Palindrome\n");
printf("4.Display\n");
printf("5.Exit\n________________\n");
printf("Enter choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:push();break;
case 2:pop();break;
case 3:pali();break;
case 4:disp();break;
case 5:exit(0);
default:printf("\nInvalid choice");
}
}
while(1);
return 0;
}
3. Define stack and show how stacks are represented? List down the applications
of stack.
Ans) A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is
named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates, etc.
A real-world stack allows operations at one end only. For example, we can place or remove a card or plate
from the top of the stack only. Likewise, Stack ADT allows all data operations at one end only. At any
given time, we can only access the top element of a stack.
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is
placed (inserted or added) last, is accessed first. In stack terminology, insertion operation is called PUSH
operation and removal operation is called POP operation.
● A Stack can be used for evaluating expressions consisting of operands and operators.
● Stacks can be used for Backtracking, i.e., to check parenthesis matching in an expression.
● It can also be used to convert one form of expression to another form.
● It can be used for systematic Memory Management.
4. Describe the types of expression and show how postfix expression evaluation is done with suitable
examples.
Arithmetic expressions
The arithmetic expression is evaluated in specific order considering the operator's precedence, and the
result of an expression will be based on the type of variable.
An arithmetic expression can be written in three different but equivalent notations, i.e., without changing
the essence or output of an expression. These notations are −
Infix Notation
We write expression in infix notation, e.g. a - b + c, where operators are used in-between operands. It is
easy for us humans to read, write, and speak in infix notation
A empty A
* + A
( *( A
B *( AB
+ *(+ AB
C *(+ ABC
) * ABC+
* * ABC+*
D empty ABC+*D*
Relational expressions
Relational operators >, <, ==,!= etc are used to compare 2 operands. Relational expressions consisting of
operands, variables, operators, and the result after evaluation would be either true or false.
Logical expressions
Relational expressions and arithmetic expressions are connected with the logical operators, and the result
after an evaluation is stored in the variable, which is either true or false.
Conditional expressions
The general syntax of conditional expression is:
Exp1? Exp2: Exp3
From the given above expressions, the first expression (exp1) is conditional, and if the condition is
satisfied, then expression2 will be executed; otherwise, expression3 will be performed.
● Postfix notation has fewer overheads of parenthesis. i.e., it takes less time for parsing.
● Postfix expressions can be evaluated easily as compared to other notations.
Module 3
1. Define Queue ADT. Compare Queue with Stack data structure.
Ans) Queue is an abstract data structure, a queue is open at both its ends. One end is always used to insert
data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out
methodology, i.e., the data item stored first will be accessed first.
The process of inserting an element in the stack is known as the push operation. Here, the deletion of
elements is known as the pop operation. A user can feasibly keep track of the last function/element of the
list in a stack using a pointer (top).
The process of inserting an element into a queue is known as the enqueue operation. Here, the process of
deleting an element is known as the dequeue operation. A user can always hold two pointers in a queue.
The front pointer points to the first inserted element that is still in the list. The second pointer is the rear
one that points to the last inserted element in the list.
2. Write a Program in ‘C’ to implement Queue data structure with its associated operations.
Ans)
#include <stdio.h>
# define SIZE 100
void enqueue();
void dequeue();
void show();
int inp_arr[SIZE];
int Rear = - 1;
int Front = - 1;
main()
{
int ch;
while (1)
{
printf("1.Enqueue Operation\n");
printf("2.Dequeue Operation\n");
printf("3.Display the Queue\n");
printf("4.Exit\n");
printf("Enter your choice of operations : ");
scanf("%d", &ch);
switch (ch)
{
case 1: enqueue();
break;
case 2: dequeue();
break;
case 3: show();
break;
case 4: exit(0);
default:
printf("Incorrect choice \n");
}
}
}
void enqueue()
{
int insert_item;
if (Rear == SIZE - 1)
printf("Overflow \n");
else
{
if (Front == - 1)
Front = 0;
printf("Element to be inserted in the Queue\n : ");
scanf("%d", &insert_item);
Rear = Rear + 1;
inp_arr[Rear] = insert_item;
}
}
void dequeue()
{
if (Front == - 1 || Front > Rear)
{
printf("Underflow \n");
return ;
}
else
{
printf("Element deleted from the Queue: %d\n", inp_arr[Front]);
Front = Front + 1;
}
}
void show()
{
if (Front == - 1)
printf("Empty Queue \n");
else
{
printf("Queue: \n");
for (int i = Front; i <= Rear; i++)
printf("%d ", inp_arr[i]);
printf("\n");
}
}
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 1
Element to be inserted in the Queue: 10
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 1
Element to be inserted in the Queue: 20
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 3
Queue:
10 20
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 2
Element deleted from the Queue: 10
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations: 3
Queue:
20
3. Explain the Concept of Circular Queue with examples. Also list the advantages of the same.
Ans) A circular queue is similar to a linear queue as it is also based on the FIFO (First In First Out)
principle except that the last position is connected to the first position in a circular queue that forms a
circle. It is also known as a Ring Buffer.
As we can see in the above image, the rear is at the last position of the Queue and front is pointing
somewhere rather than the 0th position. In the above array, there are only two elements and other three
positions are empty. The rear is at the last position of the Queue; if we try to insert the element then it will
show that there are no empty spaces in the Queue. There is one solution to avoid such wastage of memory
space by shifting both the elements at the left and adjust the front and rear end accordingly. It is not a
practically good approach because shifting all the elements will consume lots of time. The efficient
approach to avoid the wastage of the memory is to use the circular queue data structure.
Advantages
Circular Queues offer a quick and clean way to store FIFO data with a maximum size.
4. Explain the concept of Priority Queue and show how it is implemented in ‘C’ code using Arrays.
Ans) A priority queue is a special type of queue in which each element is associated with a priority value.
And, elements are served on the basis of their priority. That is, higher priority elements are served first.
However, if elements with the same priority occur, they are served according to their order in
the queue.
Hence, we will be using the heap data structure to implement the priority queue in this tutorial.
A max-heap is implemented in the following operations.
Ans) Deque:
Deque or Double Ended Queue is a type of queue in which insertion and removal of elements can either
be performed from the front or the rear. Thus, it does not follow FIFO rule (First In First Out).
Types of Deque
Input Restricted Deque
In this deque, input is restricted at a single end but allows deletion at both the ends.
Operations on a Deque
Before performing the following operations, these steps are followed.
Take an array (deque) of size n.
Set two pointers at the first position and set front = -1 and rear = 0.
If the queue is empty, both rear and front are initialized with 0. Now, both will point to the first element.
Otherwise, check the position of the front if the front is less than 1 (front < 1), then reinitialize it by front
= n - 1, i.e., the last index of the array.
If the queue is empty, both rear and front are initialized with 0. Now, both will point to the
first element.
Otherwise, increment the rear by 1. If the rear is at last index (or size - 1), then instead of
increasing it by 1, we have to make it equal to 0.
Check empty
This operation is performed to check whether the deque is empty or not. If front = -1, it
means that the deque is empty.
Check full
This operation is performed to check whether the deque is full or not. If front = rear + 1, or
front = 0 and rear = n - 1 it means that the deque is full.
The time complexity of all of the above operations of the deque is O(1), i.e., constant.
Applications of deque
● Deque can be used as both stack and queue, as it supports both operations.
● Deque can be used as a palindrome checker means that if we read the string from both ends,
● the string would be the same.
Multiple Queue:
● Multi queue is a data structure in which multiple queues are maintained.
● This type of data structures are utilized for process scheduling.
● Use one dimensional array or multidimensional array to illustrate a multiple queue.
● A multi queue implementation by using a single dimensional array along ‘m’ elements is
illustrated in Figure. Each of queues contains ‘n’ elements that are mapped to a linear array of ‘m’
elements.
● Multiple Queue can be placed in single one dimensional array.
● Insertion is possible only one end (i,e) rear & deletion is possible at other end (i,e) front of each
desired queue. This makes effective utilization of available memory space.
● Initially divide memory space into ‘n’ parts according to sizes of these ‘n’ queues.
ADVANTAGES
● Multi-line queues elements are capable of switching from one queue to another.
● Multiple-line queues use memory space more efficiently.
● With multiple lines, even large crowds are more manageable and don’t hinder the foot traffic.
DISADVANTAGES
● Multiple Queues creates illusory correlation (i,e) When there are multiple queues running at the
same time, illusion often perceive the other queue to be moving faster than the residing queue.
● Multiple-line queues encourage line-switching. when a customer is in rush, he or she may decide
to ditch the queue they have been standing in and switch to another.
● Multiple Queues rarely results in faster checkout, but does lead to momentary chaos, confusion
and even altercations between customers.
APPLICATION
Centralized service dashboard
The ability to both serve visitors and access service metrics without switching to a different platform is a
huge time-saver, and one of the top features any queue management system needs.
SMS notifications
Integrating online queue systems with SMS messaging is more important in a short span of time.
Accessing the element Direct or randomly accessed, i.e., Sequentially accessed, i.e., Traverse
Specify the array index or starting from the first node in the list
subscript. by the pointer.
Insertion and deletion of Slow relatively as shifting is Easier, fast and efficient.
element required.
2. Draw the node structure of Singly Linked List. Write the Algorithm and ‘C’ Program to show how to
insert a node at the beginning, at End and at given Location.
Ans)
Insertion in Linked List At the front/beginning of the linked list
● The new node is always added before the head of the given Linked List.
● The newly added node becomes the new head of the Linked List.
● Call the function that adds at the front of the list is push().
● The push() must receive a pointer to the head pointer because the push must change the head
pointer to point to the new node.
// Given a node prev_node, insert a new node after the given prev_node
void insertAfter(Node* prev_node, int new_data)
{
// 1. Check if the given prev_node is NULL
if (prev_node == NULL)
{
cout << "The given previous node cannot be NULL";
return;
}
// 2. Allocate new node
Node* new_node = new Node();
// 3. Put in the data
new_node->data = new_data;
// 4. Make next of new node as next of prev_node
new_node->next = prev_node->next;
// 5. move the next of prev_node as new_node
prev_node->next = new_node;
}
3. Draw the node structure of Doubly Linked List. Write the Algorithm and ‘C’ Program to show its
deletion and traversal operations.
Ans)
Ans)
5. Show how polynomials are represented using Linked List. Implement the following operations
Addition and Multiplication for any given two polynomials.
Ans)
● A polynomial is a mathematical expression consisting of a sum of terms, each term including a
variable or variables raised to a power and multiplied by a coefficient. The simplest polynomials
have one variable.
● Representation of a Polynomial: A polynomial is an expression that contains more than two
terms. A term is made up of coefficient and exponent. An example of polynomial is
P(x) = 4x3+6x2+7x+9
● A polynomial thus may be represented using arrays or linked lists.
● Array representation assumes that the exponents of the given expression are arranged from 0 to
the highest value (degree), which is represented by the subscript of the array beginning with 0.
● The coefficients of the respective exponent are placed at an appropriate index in the array.
Module 5
1. Draw the Structure of Binary Tree and show how the types of traversals are done in the binary tree for
any given expression.
Ans) Binary Tree is defined as a tree data structure where each node has at most 2 children. Since each
element in a binary tree can have only 2 children, we typically name them the left and right child.
A Binary tree is represented by a pointer to the topmost node (commonly known as the “root”) of the tree.
If the tree is empty, then the value of the root is NULL. Each node of a Binary Tree contains the following
parts:
● Data
● Pointer to left child
● Pointer to right child
Inorder Traversal:
Algorithm Inorder(tree)
● Traverse the left subtree, i.e., call Inorder(left->subtree)
● Visit the root.
● Traverse the right subtree, i.e., call Inorder(right->subtree)
Uses of Inorder Traversal:
In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get
nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal is reversed
can be used.
Example: In order traversal for the above-given figure is 4 2 5 1 3.
Preorder Traversal:
Algorithm Preorder(tree)
● Visit the root.
● Traverse the left subtree, i.e., call Preorder(left->subtree)
● Traverse the right subtree, i.e., call Preorder(right->subtree)
Uses of Preorder:
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix
expressions on an expression tree.
Example: Preorder traversal for the above-given figure is 1 2 4 5 3.
Postorder Traversal:
Algorithm Postorder(tree)
● Traverse the left subtree, i.e., call Postorder(left->subtree)
● Traverse the right subtree, i.e., call Postorder(right->subtree)
● Visit the root
Uses of Postorder:
Postorder traversal is used to delete the tree. Please see the question for the deletion of a tree for details.
Postorder traversal is also useful to get the postfix expression of an expression tree
Example: Postorder traversal for the above-given figure is 4 5 2 3 1
Ans)
#include<stdio.h>
#include<stdlib.h>
struct BST
{
int data;
struct BST *lchild;
struct BST *rchild;
};
typedef struct BST * NODE;
NODE create()
{
NODE temp;
temp = (NODE) malloc(sizeof(struct BST));
printf("\nEnter The value: ");
scanf("%d", &temp->data);
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
void main()
{
int ch, key, val, i, n;
NODE root = NULL, newnode;
while(1)
{
printf("\n~~~~BST MENU~~~~");
printf("\n1.Create a BST");
printf("\n2.Search");
printf("\n3.BST Traversals: ");
printf("\n4.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:printf("\nEnter the number of elements: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
newnode = create();
if (root == NULL)
root = newnode;
else
insert(root, newnode);
}
break;
case 2:if (root == NULL)
printf("\nTree Is Not Created");
else
{
printf("\nThe Preorder display : ");
preorder(root);
printf("\nThe Inorder display : ");
inorder(root);
printf("\nThe Postorder display : ");
postorder(root);
}
break;
case 3:search(root);
break;
case 4:exit(0);
}
}
}
Output:
~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 1
~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 3
~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 2
~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 2
~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 4
3. Explain the concept of Threaded Binary Trees and also List down the applications of Trees.
Ans) In the linked representation of binary trees, more than one half of the link fields contain NULL
values which results in wastage of storage space. If a binary tree consists of n nodes then n+1 link fields
contain NULL values. So in order to effectively manage the space, a method was devised by Perlis and
Thornton in which the NULL links are replaced with special links known as threads. Such binary trees
with threads are known as threaded binary trees. Each node in a threaded binary tree either contains a link
to its child node or thread to other nodes in the tree.
Types of Threaded Binary Tree
There are two types of threaded Binary Tree:
● One-way threaded Binary Tree
● Two- way threaded Binary Tree
Applications of trees
The following are the applications of trees:
Storing naturally hierarchical data: Trees are used to store the data in the hierarchical structure. For
example, the file system. The file system stored on the disc drive, the file and folder are in the form of
the naturally hierarchical data and stored in the form of trees.
Organize data: It is used to organize data for efficient insertion, deletion and searching. For example, a
binary tree has a logN time for searching an element.
Trie: It is a special kind of tree that is used to store the dictionary. It is a fast and efficient way for
dynamic spell checking.
Heap: It is also a tree data structure implemented using arrays. It is used to implement priority queues.
B-Tree and B+Tree: B-Tree and B+Tree are the tree data structures used to implement indexing in
databases.
Routing table: The tree data structure is also used to store the data in routing tables in the routers.
4. Define Graph. How the graphs are represented? Explain the same with suitable Example.
Ans) A graph data structure is a collection of nodes that have data and are connected to other nodes. For
example. On facebook, everything is a node. That includes User, Photo, Album, Event, Group, Page,
Comment, Story, Video, Link, (Note...anything that has data is a node). Every relationship is an edge from
one node to another. Whether you post a photo, join a group, like a page, etc., a new edge is created for
that relationship. All of facebook is then a collection of these nodes and edges. This is because facebook
uses a graph data structure to store its data.
More precisely, a graph is a data structure (V, E) that consists of a collection of vertices V & a collection
of edges E, represented as ordered pairs of vertices (u,v)
In the graph,
V = {0, 1, 2, 3}
E = {(0,1), (0,2), (0,3), (1,2)}
G = {V, E}
Graph Terminology
Adjacency: A vertex is said to be adjacent to another vertex if there is an edge connecting them. Vertices
2 and 3 are not adjacent because there is no edge between them.
Path: A sequence of edges that allows you to go from vertex A to vertex B is called a path. 0-1, 1-2 and
0-2 are paths from vertex 0 to vertex 2.
Directed Graph: A graph in which an edge (u,v) doesn't necessarily mean that there is an edge (v, u) as
well. The edges in such a graph are represented by arrows to show the direction of the edge.
5. Define the types of Graph Traversal methods and explain the same with algorithms and example.
DFS Algorithm
A standard DFS implementation puts each vertex of the graph into one of two categories:
● Visited
● Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
The DFS algorithm works as follows:
● Start by putting any one of the graph's vertices on top of a stack.
● Take the top item of the stack and add it to the visited list.
● Create a list of that vertex's adjacent nodes.
● Add the ones which aren't in the visited list to the top of the stack.
● Keep repeating steps 2 and 3 until the stack is empty.
BFS Algorithm
A standard BFS implementation puts each vertex of the graph into one of two categories:
● Visited
● Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
The algorithm works as follows:
● Start by putting any one of the graph's vertices at the back of a queue.
● Take the front item of the queue and add it to the visited list.
● Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the
back of the queue.
● Keep repeating steps 2 and 3 until the queue is empty.
● The graph might have two different disconnected parts so to make sure that we cover every
vertex, we can also run the BFS algorithm on every node.