Skip to content

Commit 1f49fca

Browse files
authored
Add files via upload
1 parent c30c9d3 commit 1f49fca

File tree

2 files changed

+116
-0
lines changed

2 files changed

+116
-0
lines changed

Assignment5/150101051_2.cpp

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
/* Submitted by
2+
Name:REDDI HAREESH
3+
Roll Number:150101051
4+
*/
5+
//I am starting indexes of nodes from 0 and there is always a path from a node to itself
6+
#include<iostream>
7+
#include <list>
8+
using namespace std;
9+
10+
class Graph
11+
{
12+
int V;
13+
list<int> *adjacent;
14+
int isReachableUtil(int visited[], int a,int b);
15+
16+
public:
17+
Graph(int V);
18+
void addEdge(int v, int w);
19+
int isReachable(int a, int b);
20+
};
21+
22+
Graph::Graph(int V)
23+
{
24+
this->V = V;
25+
adjacent = new list<int>[V];
26+
}
27+
28+
void Graph::addEdge(int a, int b)
29+
{
30+
adjacent[a].push_back(b); // Add b to a list.
31+
}
32+
33+
int Graph::isReachableUtil(int visited[], int a,int b)
34+
{
35+
if(a==b)
36+
{
37+
return 1;
38+
}
39+
visited[a] = 1;
40+
41+
list<int>::iterator itr;
42+
43+
for(itr = adjacent[a].begin(); itr != adjacent[a].end(); ++itr)
44+
{
45+
if (!visited[*itr] && isReachableUtil(visited,*itr,b))
46+
return 1;
47+
}
48+
49+
return 0;
50+
}
51+
int Graph::isReachable(int a, int b)
52+
{
53+
int visited[V];
54+
55+
for(int i = 0; i < V; i++)
56+
{
57+
visited[i] = 0;
58+
}
59+
60+
return isReachableUtil(visited,a,b);
61+
}
62+
int main()
63+
{ int n,e,i,j,u,v;
64+
//create a graph
65+
cout<<"Enter number of nodes of the graph:";
66+
cin>>n;
67+
cout<<"\n";
68+
Graph g(n);
69+
cout<<"Enter number of edges of the graph:";
70+
cin>>e;
71+
cout<<"\n";
72+
int matrix[n][n];
73+
for(i=0;i<n;i++)
74+
{
75+
for(j=0;j<n;j++)
76+
{
77+
matrix[i][j]=0;
78+
}
79+
}
80+
if(e>0)
81+
{
82+
cout<<"Enter the Edges:\n";
83+
}
84+
for(i=0;i<e;i++)
85+
{
86+
cin>>u>>v;
87+
matrix[u][v]=1;
88+
g.addEdge(u, v);
89+
}
90+
cout<<"\n";
91+
//Matrix representation of the graph
92+
cout<<"The matrix representation of the graph is:\n";
93+
for(i=0;i<n;i++)
94+
{
95+
for(j=0;j<n;j++)
96+
{
97+
cout<<matrix[i][j];
98+
cout<<"\t";
99+
}
100+
cout<<"\n";
101+
}
102+
103+
for(i=0;i<n;i++)
104+
{
105+
for(j=0;j<n;j++)
106+
{
107+
if(g.isReachable(i,j))
108+
cout<< "\nThere is a path from node " << i << " to node " << j;
109+
else
110+
cout<< "\nThere is no path from node " << i << " to node " << j;
111+
}
112+
cout<<"\n";
113+
}
114+
cout<<"\n\n";
115+
return 0;
116+
}

Assignment5/assignment5_DFS_BFS.pdf

170 KB
Binary file not shown.

0 commit comments

Comments
 (0)