You are on page 1of 4

Practical Worksheet 3.

UID:- 19BCS2241
Student Name:- Kartik Guleria
Section/Group:- CSE-9/A
Branch:- CSE
Subject Code:- CSP-309
Subject Name:- DAA Lab

1. Aim/Overview of the practical:

Code and analyze to do a depth-first search (DFS) on an undirected graph. Ipmleemnting an


application of DFS such as

(i) to find the topological sort of a directed acyclic graph, OR

(ii) to find a path fromsource to goal in a amze.

Depth First Search (DFS) AlgorithmDepth First Search (DFS) algorithmtraverses a graph in a depth
ward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs
in any iteration.

Algorithm :

Step 1: SET STATUS = 1 (ready state) for each node in G

Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)

Step 3: Repeat Steps 4 and 5 until STACK is empty

Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)

Step 5: Push on the stack all the neighbours of N that are in the ready state (whose STATUS =
1) and set their STATUS = 2 (waiting state) [END OF

LOOP] Step 6: EXIT


Topological Sort :

The topological sorting for a directed acyclic graph is the linear ordering of vertices. For every
edge U-V of a directed graph, the vertex u will come before vertex v in the ordering

Algorithm:

topoSort(u, visited, stack)

Input − The start vertex u, An array to keep track of which node is visited or not. A stack to
store nodes. Output − Sorting the vertices in topological sequence in the stack.

Begin

mark u as visited for all vertices v which is adjacent with u,

do if v is not visited, then topoSort(c, visited, stack)

done

push u into a stack

End

performTopologicalSorting(Graph)

Input − The given directed acyclic graph.

Output − Sequence of nodes.

Begin

initially mark all nodes as unvisited for all nodes v of the graph,

do if v is not visited, then topoSort(i, visited, stack)

done

pop and print all elements fromthe

stack End
Code:

#include <bits/stdc++.h>

using namespace std;

class Graph

public:

map<int, bool> visited;

map<int, list<int> > adj;

void addEdge(int v, int w);

void DFS(int v);

};

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

adj[v].push_back(w);

void Graph::DFS(int v)

visited[v] = true;

cout << v << " ";

list<int>::iterator i;

for (i = adj[v].begin(); i != adj[v].end(); ++i)

if (!visited[*i])

DFS(*i); }

int main(
{

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 fromvertex 2) \n";

g.DFS(2)

Return 0; }

Output:

You might also like