-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDFSBFS.cpp
More file actions
172 lines (147 loc) · 2.97 KB
/
DFSBFS.cpp
File metadata and controls
172 lines (147 loc) · 2.97 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#include <iostream>
#include <vector>
using namespace std;
int st[10],top=-1,Q[10],front=-1,rear=-1;
void insertQ(int v)
{
if(front==-1 && rear==-1)
{
front=0;
rear=0;
Q[rear]=v;
}
else if(rear<9)
{
Q[++rear]=v;
}
else
{
cout<<"Queue Overflow";
}
}
int deleteQ()
{
int v=-1;
if(front == (rear+1))
{
cout<<"Queue Empty";
}
else if(front==-1 && rear == -1)
{
cout<<"Queue Empty";
}
else
{
v=Q[front];
front++;
}
return v;
}
void push(int v)
{
if(top<9)
{
st[++top]=v;
}
else
{
cout<<"Stack is full";
}
}
int pop()
{
int v=-1;
if(top!=-1)
{
v=st[top];
top--;
}
else
{
cout<<"Stack is empty";
}
return v;
}
int main() {
int V, E;
char Dir;
cout << "Enter How many vertices? ";
cin >> V;
vector<vector<int>> adjMat(V + 1, vector<int>(V + 1, 0));
//int adjMat[V + 1][V + 1];
cout << "Graph is directed/undirected (D/U): ";
cin >> Dir;
cout << Dir;
cout << "Enter Number of edges: ";
cin >> E;
int sr, ds, wt;
for (int i = 0; i < E; i++) {
cout << "Enter source, destination, and weight of the edge " << i + 1 << ": ";
cin >> sr >> ds >> wt;
if (sr >= 1 && sr <= V && ds >= 1 && ds <= V) {
adjMat[sr][ds] = wt;
if (Dir == 'U')
adjMat[ds][sr] = wt;
} else {
cout << "Enter correct vertices for the edge." << endl;
i--;
}
}
// Print adjacency matrix
cout << "Adjacency Matrix is: " << endl;
for (int i = 1; i <= V; i++) {
for (int j = 1; j <= V; j++) {
cout << adjMat[i][j] << " ";
}
cout << endl;
}
//DFS
int visited[V+1];
int sv;
cout<<"Enter from which vertex you want to start traversal: ";
cin>>sv;
for(int i=1;i<=V;i++)
{
visited[i]=0;
}
push(sv);
while(top!=-1)
{
sv=pop();
if(visited[sv]==0)
{
cout<<sv<<" ->";
visited[sv]=1;
for(int i=1;i<=V;i++)
{
if(adjMat[sv][i]>0)
{
push(i);
}
}
}
}
cout<<endl;
cout<<"Enter from which vertex you want to start traversal: ";
cin>>sv;
for(int i=1;i<=V;i++)
{
visited[i]=0;
}
insertQ(sv);
visited[sv]=1;
while(front!=(rear+1))
{
sv=deleteQ();
cout<<sv<<" ->";
for(int i=1;i<=V;i++)
{
if((adjMat[sv][i]>0) && visited[i]==0)
{
insertQ(i);
visited[i]=1;
}
}
}
return 0;
}