-
Notifications
You must be signed in to change notification settings - Fork 0
/
depth first search.cpp
70 lines (70 loc) · 1009 Bytes
/
depth first search.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream>
using namespace std;
struct graph
{
int v;
int e;
int adj[100][100];
};
void adjmatrix(graph *g, int v, int e)
{
for(int i = 0; i < v; i++)
{
for(int j = 0; j < v; j++)
{
g->adj[i][j] = 0;
}
}
int val1,val2;
for(int i=0;i<e;i++)
{
cout<<"which two vertices you want to join: ";
cin>>val1;
cin>>val2;
g->adj[val1][val2]=1;
g->adj[val2][val1]=1;
}
for(int i = 0; i < v; i++)
{
for(int j = 0; j < v; j++)
{
cout << g->adj[i][j] << " ";
}
cout << endl;
}
}
void dfs(graph *g,int u,int v,int *vis)
{
vis[u]=1;
cout<<u;
for(int i=0;i<g->v;i++)
{
if(vis[i]==0 &&g->adj[u][i]==1)
{
dfs(g,i,v,vis);
}
}
}
void dfstraversal(graph *g,int v)
{
int *vis=new int;
for(int i=0;i<g->v;i++)
{
vis[i]=0;
}
for(int i=0;i<g->v;i++)
{
if(vis[i]==0)
{
dfs(g,i,v,vis);
}
}
}
int main()
{
graph *g = new graph;
g->v=6;
adjmatrix(g, 4, 5);
dfstraversal(g,4);
delete g; // Deallocate memory
}