-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.cpp
More file actions
62 lines (60 loc) · 1.24 KB
/
Copy pathbfs.cpp
File metadata and controls
62 lines (60 loc) · 1.24 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
#include<bits/stdc++.h>
using namespace std;
class graph
{
int v;
list<int>* adj;
public:
graph(int v)
{
this->v=v;
adj=new list<int>[v];
}
void addEdge(int v,int w)
{
adj[v].push_back(w);
adj[w].push_back(v);
}
vector<int> BFS(int s)
{ vector<int> ve;
bool *visited=new bool[v];
for(int i=0;i<v;i++)
visited[i]=false;
queue<int>q;
visited[s]=true;
q.push(s);
list<int> :: iterator i;
while(!q.empty())
{
s=q.front();
ve.push_back(s);
//cout<<s<<" "<<endl;
q.pop();
for(i=adj[s].begin();i!=adj[s].end();i++)
{cout<<"adj to "<<s<<" :";
if(!visited[*i])
{
visited[*i]=true;
cout<<*i<<" "<<endl;
q.push(*i);
}
}
cout<<endl;
}
return ve;
}
};
int main()
{vector<int> v;
graph g(6);
g.addEdge(0,1);
g.addEdge(4,2);
g.addEdge(1,2);
g.addEdge(2,5);
g.addEdge(4,3);
g.addEdge(3,3);
g.addEdge(5,1);
v=g.BFS(4);
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
}