I am implementing BFS algorithm. I wrote this code in my IDE.
SYSTEM:
Windows 10
Dev c++
May be error in bfs() function.I posted my all code just because of reference.
My C++ code :
#include<bits/stdc++.h>
using namespace std;
class Graph{
int v; // number of vertices
vector<int>*adj;
public:
/**
* Constructor to initialize the graph.
* @param v an integer: number of nodes in the graph
*/
Graph(int V){
this->v=V;
this->adj=new vector<int>[V];
}
/**
* This function add a new edge to the graph.
* @param u an integer: representing a node in the graph.
* @param v an integer: representing a node in the graph.
* @param biDir a bool: true denotes bidirectional edge, unidirectional otherwise.
*/
void addEdge(int u,int v,bool biDir=false){
adj[u].push_back(v);
if(biDir)
adj[v].push_back(u);
}
/**
* This function traverse the given graph using BFS traversal technique.
* @param src a node: function starts traversing from this node.
*/
void bfs(int src){
// create a array of boolean to keep track of visited nodes.
vector<bool>visited(this->v,false);
// visited[0]=true;
// make a queue and insert src into it
queue<int>q;
q.push(src); // insert src into queue
// mark first node as visited
visited[src]=true;
while(!q.empty()){
int node=q.front();
// visit
cout<<node<<" ";
// remove this node from queue
q.pop();
// visit every node adjacent to node 'node'
// if that node not visited then visit and enque it.
for(int adjNode:adj[node]){
if(!visited[adjNode]){
visited[adjNode]=true;
q.push(adjNode);
}
}
}
}
void print(){
// for every vertex
for(int i=1;i<this->v;i++){
// every connected edge from vertex
cout<<i<<"-> ";
for(int node:adj[i]){
cout<<node<<" ";
}
cout<<endl;
}
}
};
int main(){
Graph g(5+1);
g.addEdge(1,2);
g.addEdge(1,4);
g.addEdge(4,6);
g.addEdge(3,6);
g.addEdge(2,5);
g.addEdge(5,2);
g.addEdge(6,3);
g.addEdge(6,4);
g.print();
cout<<endl;cout<<endl;cout<<endl;cout<<endl;
g.bfs(1);
return 0;
}
Although this program is compiling fine. But while running, only print() function executes. Function bfs() does not executes.
It produces the following OUTPUT: generated by print() function.
1-> 2 4
2-> 5
3-> 6
4-> 6
5-> 2
When i changed this code in bfs()
vector<bool>visited(this->v,false);
TO this
bool visited[this->v];
for(int i=0;i<this->v;i++)
visited[i]=false;
this code also does not executes bfs().
As i can see, you are using 1
based indexing for node value. I mean you are not considering 0
as a node in your graph. Any node in your graph starts from 1
. While initializing graph you can set the value of graph size equals to number of nodes + 1
.
I mean,
Graph(int V){
this->v=V+1;
this->adj=new vector<int>[V];
}
This can solve your problem.