-
Notifications
You must be signed in to change notification settings - Fork 34
/
BFS(Graph)
49 lines (46 loc) · 954 Bytes
/
BFS(Graph)
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
#include <iostream>
#include <queue>
using namespace std;
void dfs(int **edge, int v, int sv, bool *visited, queue<int> q){
q.push(sv);
while(q.size()){
visited[q.front()]=true;
cout<<q.front()<<" ";
for(int i=0;i<v;i++){
if(i==q.front()){
continue;
}
if(visited[i]==true){
continue;
}
if(edge[q.front()][i]==1){
q.push(i);
visited[i]=true;
}
}
q.pop();
}
}
int main() {
int v, e;
cin >> v >> e;
int **edge=new int*[v];
for(int i=0;i<v;i++){
edge[i]=new int[v];
for(int j=0;j<v;j++)
edge[i][j]=0;
}
for(int i=0;i<e;i++){
int f,s;
cin>>f>>s;
edge[f][s]=1;
edge[s][f]=1;
}
bool *visited = new bool[v];
for(int i=0;i<v;i++){
visited[i]=false;
}
queue<int> q;
dfs(edge,v,0,visited,q);
return 0;
}