-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgraph_creation.cpp
More file actions
144 lines (142 loc) · 2.49 KB
/
graph_creation.cpp
File metadata and controls
144 lines (142 loc) · 2.49 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <iostream>
#include<queue>
using namespace std;
class gnode{
int vertex;
gnode* next;
friend class graph;
};
class graph{
gnode* head[20];
int n;
int visited[20];
int visit[20];
public:
graph()
{
cout<<"Enter the number of vertices";
cin>>n;
for(int i=0;i<n;i++){
head[i] = new gnode();
head[i]->vertex=i;
}
}
void create()
{
for(int i=0;i<n;i++){
gnode* temp = head[i];
int v;
char ch;
do{
cout << "Enter the adjacent element to "<<i << ":"<<endl;
cin >> v;
if (i==v)
cout<<"Self Loop is not allowed"<<endl;
else{
if (v == 999)
continue;
gnode* curr = new gnode();
curr->vertex = v;
temp->next = curr;
temp = temp->next;
}
cout << "Do you want to enter more vertices(y/n)";
cin >> ch;
}while(ch=='y');
}
dfs();
}
void dfs(){
int node;
cout << "Enter the starting vertex";
cin >> node;
for (int i = 0;i<n;i++)
visited[i] = 0;
dfs(node);
bfs(node);
}
void dfs(int v){
int node;
gnode* temp = head[v]->next;
visited[v] = 1;
cout << v << endl;
while (temp != NULL){
node = temp->vertex;
if (!visited[node])
dfs(node);
temp = temp->next;
}
}
void bfs(int v)
{
queue<int> q;
q.push(v);
for (int i = 0; i < n; i++)
visit[i] = 0;
while (!q.empty())
{
int current = q.front();
q.pop();
if (!visit[current])
{
cout << current << "\n";
visit[current] = 1;
gnode *temp = head[current]->next;
while (temp != NULL)
{
int w = temp->vertex;
if (!visit[w])
{
q.push(w);
}
temp = temp->next;
}
}
}
}
};
int main(){
graph g;
g.create();
return 0;
}
/*
PS C:\Users\Ahad\Documents\GitHub\ADS-With-cpp> g++ graph_creation.cpp
PS C:\Users\Ahad\Documents\GitHub\ADS-With-cpp> ./a.exe
Enter the number of vertices6
Enter the adjacent element to 0:
1
Do you want to enter more vertices(y/n)y
Enter the adjacent element to 0:
3
Do you want to enter more vertices(y/n)n
Enter the adjacent element to 1:
2
Do you want to enter more vertices(y/n)n
Enter the adjacent element to 2:
4
Do you want to enter more vertices(y/n)n
Enter the adjacent element to 3:
2
Do you want to enter more vertices(y/n)n
Enter the adjacent element to 4:
999
Enter the adjacent element to 5:
3
Do you want to enter more vertices(y/n)y
Enter the adjacent element to 5:
4
Do you want to enter more vertices(y/n)n
Enter the starting vertex0
DFS
0
1
2
4
3
BFS
0
1
3
2
4*/