Professional Documents
Culture Documents
EXPERIMENT2
EXPERIMENT2
• A vertex in a graph can be connected to any number of other vertices using edges.
CODE
#include<iostream>
#include<list>
#include<memory> using
namespace std; class
Graph{ int V;//No. of
vertices
list<int>* adj;//Pointer to an array containing adjacency lists
void DFSUtil(int v, bool visited[]);//A function used by DFS
public:
Graph(int V);//Constructor
void addEdge(int v, int w);//Function to add an edge to graph
void DFS();//Prints DFS traversal of the complete graph
};
Graph::Graph(int V){
this->V = V; adj =
new list<int>[V];
}
void Graph::addEdge(int v, int w){ adj[v].push_back(w);//Add
w to v’s list.
}
void Graph::DFSUtil(int v, bool visited[]){
visited[v]=true;//Mark the current node as visited and print it cout<<v<<"
";
list<int>::iterator i;//Recur for all the vertices adjacent to this vertex
for(i=adj[v].begin(); i!=adj[v].end(); ++i) if (!visited[*i])
DFSUtil(*i, visited);
}
void Graph::DFS(){//The function to do DFS traversal. It uses recursive DFSUtil()
bool *visited=new bool[V];//Mark all the vertices as not visited for(int i=0; i<V;
i++) visited[i]=false;
OUTPUT
EXPERIMENT -19
Aim-Program to traverse graphs using BFS.
Hardware and Software Requirement- CPU , C++ , Dev C++ , Screen, Mouse,
Theory
A graph is a pair (V, E), where V is a set of nodes, called vertices and E is a collection of pairs of
vertices, called edges. Vertices and edges are positions and store elements. Removal of an edge
from a circuit or connected graph creates a sub-graph that is a tree.
The graphs are classified into various categories such as directed, non-directed, connected,
nonconnected, simple and multi-graph. Properties of a graph are as follows:
• A vertex in a graph can be connected to any number of other vertices using edges.
CODE
#include<iostream>
#include<list> using
namespace std; class
Graph{ int V;//No. of
vertices list<int>
*adj;//Pointer to an
array containing
adjacency lists
public:
Graph(int V);//Constructor
void addEdge(int v, int w); //Function to add an edge to graph
void BFS(int s);//Print BFS traversal from a given source s
};
Graph::Graph(int V){
this->V=V; adj=new
list<int>[V];
}
void Graph::addEdge(int v, int w){ adj[v].push_back(w);//Add
w to v’s list.
}
void Graph::BFS(int s)
bool *visited=new bool[V];//Mark all the vertices as not visited
for(int i=0; i<V; i++) visited[i]=false;
list<int>queue;//Create a queue for BFS
visited[s]=true;//Mark the current node as visited and enqueue it queue.push_back(s);
list<int>::iterator i;//'i' will be used to get all adjacent vertices of a vertex
cout<<"\t"; while(!queue.empty()){
s=queue.front();//Dequeue a vertex from queue and print it
cout<<s<<" "; queue.pop_front();
for(i=adj[s].begin(); i!=adj[s].end(); ++i){ if(!visited[*i]){
OUTPUT