-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS and DFS.cpp
160 lines (130 loc) · 2.17 KB
/
BFS and DFS.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
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
#include<iostream>
#include<queue>
using namespace std;
struct node
{
int data;
node* next;
};
void dfs(int v,node** arr,bool visit[])
{
//Vertex v is visited
visit[v-1] = true;
cout<<v<<" ";
node* q;
q = new node;
q = *(arr+v-1);
while(q!=NULL)
{
if(visit[(q->data)-1]==false) //Unvisited Node
{
dfs((q->data),arr,visit);
}
else //Visited Node
{
q = q->next;
}
}
return ;
}
void bfs(int v,node** arr,bool visit[],queue<int> qu)
{
node* p;
int x;
//Vertex v has been visited
visit[v-1] = true;
cout<<v<<" ";
qu.push(v);
while(!qu.empty())
{
x = qu.front();
qu.pop();
p = *(arr+x-1);
while(p!=NULL)
{
if(visit[(p->data)-1]==false)
{
visit[(p->data)-1] = true;
cout<<p->data<<" ";
qu.push(p->data);
}
p = p->next;
}
}
return ;
}
int main()
{
freopen("ip.txt","r",stdin);
int n,m,a,b,i;
queue<int> qu;
cout<<"\nEnter how many vertices:";
cin>>n;
node* arr[n],*v1,*v2,*v3,*v4,*temp,*temp1;
bool visited[n];
for(i=0;i<n;i++)
{
visited[i]=false;
arr[i] = NULL;
}
cout<<"\n\nHow many unique edge connections?:";
cin>>m;
//Creation of node connections
while(m--)
{
cout<<"\nEnter incident edges(with spaces):";
cin>>a>>b;
//Put vertex b in adjacency list of vertex a
if(arr[a-1]==NULL)
{
temp1 = new node;
temp1->data = b;
temp1->next = NULL;
arr[a-1] = temp1;
}
else
{
temp = arr[a-1];
while(temp->next!=NULL)
{
temp = temp->next;
}
temp1 = new node;
temp1->data = b;
temp1->next = NULL;
temp->next = temp1;
}
//Put vertex a in adjacency list of vertex b
if(arr[b-1]==NULL)
{
temp1 = new node;
temp1->data = a;
temp1->next = NULL;
arr[b-1] = temp1;
}
else
{
temp = arr[b-1];
while(temp->next!=NULL)
{
temp = temp->next;
}
temp1 = new node;
temp1->data = a;
temp1->next = NULL;
temp->next = temp1;
}
}
//Calling DFS function
cout<<"\n\nThe DFS order is:\n";
dfs(1,arr,visited);
//Reset all nodes as unvisited
for(i=0;i<n;i++)
{
visited[i] = false;
}
//Calling BFS function
cout<<"\n\nThe BFS order is:\n";
bfs(1,arr,visited,qu);
return 0;
}