Skip to content

Commit adea73e

Browse files
authored
Update DFS_BFS.cpp
1 parent 6054c87 commit adea73e

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

Algorithms/DFS_BFS.cpp

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,69 @@
11
#include<bits/stdc++.h>
2+
#define MAX 100001
23
using namespace std;
34

4-
vector<int> v[100001];
5-
int visited[100001]={0};
65

7-
void dfs(int start)
8-
{
6+
// intializing the graph
7+
vector<int> v[MAX];
8+
9+
// intializing the visited array
10+
int visited[MAX]={0};
11+
12+
void dfs(int start){
13+
14+
915
cout<<start<<" ";
16+
17+
// mark the current node as visited
1018
visited[start]=1;
19+
1120
for(int i=0;i<v[start].size();i++)
1221
{
22+
23+
// loop through all the nodes connected to current node
24+
// if the node is not alreay marked visit it
1325
if(!visited[v[start][i]])
1426
{
27+
1528
dfs(v[start][i]);
1629
}
1730
}
1831
}
1932

2033
void bfs(int start)
2134
{
35+
36+
2237
int current;
2338
queue<int> q;
39+
40+
// push the source node to the queue
2441
q.push(start);
42+
43+
// loop till the queue is empty
2544
while(q.size()!=0)
2645
{
46+
47+
// set current node to the first node in the queue
2748
current = q.front();
2849
q.pop();
50+
51+
// if current node isn't marked already visit it
2952
if(!visited[current])
3053
{
3154
cout<<current<<" ";
3255
visited[current]=1;
3356
}
57+
3458
for(int i=0;i<v[current].size();i++)
3559
{
60+
61+
62+
3663
if(!visited[v[current][i]])
3764
{
65+
66+
// push all nodes adjacent to the current node to the queue
3867
cout<<v[current][i]<<" ";
3968
visited[v[current][i]]=1;
4069
q.push(v[current][i]);

0 commit comments

Comments
 (0)