I'm trying to implement a BFS on adjacency matrix of undirected unweighted graph which returns the number of nodes visited. I've come up with this till now but I think this is not right as when I print out the top/ visited node, I'm getting multiple occurrences of some nodes as well as it's not sorted. I've read somewhere that BFS is a topological sort and the order I get is not sorted.
int BFS(std::vector<std::vector<int> > &matrix, int start)
{
std::vector<bool> visited(matrix.size(), false);
std::queue<int> Q;
Q.push(start);
int count = 0;
while( ! Q.empty())
{
int top = Q.front(); Q.pop();
visited[top] = true; count++;
for (int i = 0; i < matrix.size(); ++i)
{
if(matrix[top][i] != 0 && (! visited[i]) )
{
Q.push(i);
}
}
}
return count;
}
Approach: Create a matrix of size n*n where every element is 0 representing there is no edge in the graph. Now, for every edge of the graph between the vertices i and j set mat[i][j] = 1. After the adjacency matrix has been created and filled, find the BFS traversal of the graph as described in this post.
The Time complexity of BFS is O(V + E) when Adjacency List is used and O(V^2) when Adjacency Matrix is used, where V stands for vertices and E stands for edges.
For directed graphs, too, we can prove nice properties of the BFS and DFS tree that help to classify the edges of the graph. For BFS in directed graphs, each edge of the graph either connects two vertices at the same level, goes down exactly one level, or goes up any number of levels.
Put differently, BFS runs in linear time in the size of the graph. Proof: It explores every vertex once. Once a vertex is marked, it's not explored again. It traverses each edge twice.
Instead of setting visited
node to true after popping the queue, you should set it when you insert it to the queue, and add count inside as well, as to prevent double counting of some nodes. Please refer to the following:
//..previous lines
Q.push(start);
visited[start] = true;
int count = 1;
while(!Q.empty()){
int top = Q.front(); Q.pop();
for (int i = 0; i < matrix.size(); ++i){
if(matrix[top][i] != 0 && (! visited[i]) ){
Q.push(i);
visited[i] = true;
count++;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With