Documente Academic
Documente Profesional
Documente Cultură
Ex. No. 10
Implementation of graph traversal
(Date)
Aim
Implementation of BFS graph traversal.
Description
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The
only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node
again. To avoid processing a node more than once, we use a boolean visited array.
Algorithm
Algorithmic Steps
Step 4: If the removed node has unvisited child nodes, mark them as visited and insert the
unvisited children in the queue.
Program
// C++ program to print DFS traversal from
#include<iostream>
#include<list>
class Graph
// adjacency lists
list<int> *adj;
public:
// reachable from v
};
Graph::Graph(int V)
this->V = V;
// print it
visited[v] = true;
// to this vertex
list<int>::iterator i;
if (!visited[*i])
DFSUtil(*i, visited);
void Graph::DFS(int v)
visited[i] = false;
DFSUtil(v, visited);
int main()
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.DFS(2);
return 0;
Output
Following is Depth First Traversal (starting from vertex 2)
2013
Link
https://drive.google.com/drive/u/0/folders/13FUOcxurgAdx6JIWjAfFVX19BTF5YDMX