Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- vector<int> adj[100]; //adjacency list (an array of vectors)
- bool visited[100]; //to keep track which vertices are visited
- queue<int> Q; //queue of incoming vertices to check
- void BFS(int v){
- Q.push(v); //insert root vertex (vertex 0)
- visited[v]=true; //mark as visited
- while(!Q.empty()){ //repeat while the queue is not empty
- int now=Q.front(); //take frontmost vertex as current vertex
- cout<<now<<" "; //prints out current vertex
- Q.pop(); //remove the frontmost element
- //check each vertex connected to current vertex
- for(int i=0;i<adj[now].size();i++){
- int x=adj[now][i];
- if(!visited[x]){ //if vertex is not visited, add it to the (back of) queue
- visited[x]=true;
- Q.push(x);
- }
- }
- }
- }
- int main()
- {
- int V,E; //specify no of vertices,V and edges,E
- cin>>V>>E;
- //create adjacency list (input E pairs of vertices that are connected by an edge)
- for(int i=0;i<E;i++){
- int a,b;
- cin>>a>>b;
- adj[a].push_back(b);
- adj[b].push_back(a);
- }
- BFS(0); //start BFS from vertex 0
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement