19BCS2206 (Worksheet 3.1)
19BCS2206 (Worksheet 3.1)
19BCS2206 (Worksheet 3.1)
Subject name: Design & Analysis of Algo. Lab Subject code: CSP-309
Aim:
Code to analyze to do a depth-first search (DFS) on an undirected graph. Implementing
an application of DFS such as:
a) To find the topological sort of directed acyclic graph, OR
b) To find a path from source to goal in a maze.
Algorithm:
Algorithm:
(Topology Sort)
Step 1: Create the graph by calling addEdge(a,b).
Step 2: Call the topologicalSort( )
Step 3: Create a stack and a Boolean array named as visited [ ];
Step 4: Mark all the vertices as not visited i.e. initialize visited [ ] with 'false' value.
Step 5: Call the recursive helper function topologicalSortUtil() to store Topological Sort
starting from all vertices one by one.
Step 6: def topologicalSortUtil(int v, bool visited[],stack<int> &Stack):
Step 7: Mark the current node as visited.
Step 8: Recur for all the vertices adjacent to this vertex.
Step 9: Push current vertex to stack which stores result.
Step 10: At last, after return from the utility function, print contents of stack.
Worksheet 3.1 1
Cod
(Depth First Search)
#include <bits/stdc++.h>
using namespace std;
class Graph
{
public:
map<int, bool> visited;
map<int, list<int>> adj;
void add(int v, int w);
void DFS(int v);
};
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;
int n,a,b
cout<<"Enter number of adjacent pair of
nodes:"; cin>>n;
for(int i=1;i<=n;i++){
cout<<"Pair"<<i<<":";
cin>>a>>b;
g.add(a,b);
}
int s;
cout<<"Enter Starting node(root):";
cin>>s;
g. DFS(s);
return 0;
}
Worksheet 2
OUTPU
Worksheet 3
Cod
(Topology Sorting)
#include <bits/stdc++.h>
using namespace std;
Class Graph{
Int V;
List<int>*adj;
Void topological Sort Util(int v,bool visited[],stack<int>&
Stack); public:
Graph(int V);
void add(int v, int w); void topological Sort();
};
Graph::Graph(int V){
this->V = V;
adj = new list<int>[V];
}
void Graph::add(int v, int w)
{ adj[v].push_back(w);
}
Visited[v] = true
List<int>::iterator i;
for (i = adj[v].begin(); i ! =adj[v].end(); +
+i) if (!visited [*i])
topological Sort Util(*i, visited ,Stack);
Stack.push(v);
}
Worksheet 4
OUTPU
(Topology Sorting)
Learning Outcomes:
a) I learnt how to perform depth first traversal.
b) I learnt how to perform traversing in a graph
c) I learnt how topological sorting is done.
Worksheet 5