0% found this document useful (0 votes)
7 views

Exp NO 8

Uploaded by

papu varsha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Exp NO 8

Uploaded by

papu varsha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

DATE Ex.

NO: 8: Graph Traversals

AIM:
To write a program to implement Graph Traversals using Breath First Search tree
algorithm.

ALGORITHM :

1. Start at some node, and is now our current node.

2. State that our current node is ‘visited’.


3. Now look at all nodes adjacent to our current node.

4. If we see an adjacent node that has not been ‘visited’, add it to the stack.
5. Then pop of the top node on the stack and traverse to it.
And go back to step 1
PROGRAM:

// C++ program to print DFS traversal from


// a given vertex in a given graph
#include <bits/stdc++.h>
using namespace std;

// Graph class represents a directed graph


// using adjacency list representation
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;

// function to add an edge to graph


void addEdge(int v, int w);

// DFS traversal of the vertices


// reachable from v
void DFS(int v);
};

void Graph::addEdge(int v, int w)


{
adj[v].push_back(w); // Add w to v’s list.
}

void Graph::DFS(int v)
{
// Mark the current node as visited and
// print it
visited[v] = true;
cout<< "";

// Recur for all the vertices adjacent


// to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}
// Driver code
int main()
{
// Create a graph given in the above diagram
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

cout << "Following is Depth First Traversal"


" (starting from vertex 2) \n";
g.DFS(2);

return 0;
}

OUTPUT :

novice@it002:~$ g++ bfs.cpp

novice@it002:~$ ./a.out

Following is Breadth First Traversal (starting from vertex 2)


2031
RESULT:
Thus the C++ program to Graph Traversals tree –BFS was executed and verified
successfully

You might also like