I'm testing around with BFS and I understand the basic algorithm to display the nodes in visited order, but am struggling to get the nodes used to visit that particular node. Any hints?
#include<iostream>
#include <list>
usingnamespace std;
class Graph
{
int V;
list<int> *adj;
public:
Graph(int V);
void addEdge(int v, int w);
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = newbool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
list<int>::iterator i;
while(!queue.empty())
{
s = queue.front();
cout << s << " "; //displays in order BFS as expected
queue.pop_front();
// Get all adjacent vertices, if it has not been visited,
// then mark it visited and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
if (!visited[*i])
{ cout<<s<<" "; //doesn't work to display source of where this was visited from, surprisingly
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = newbool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
cout << "null -> " << s << '\n';
list<int>::iterator i;
while(!queue.empty())
{
s = queue.front();
queue.pop_front();
// Get all adjacent vertices, if it has not been visited,
// then mark it visited and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
if (!visited[*i]) {
cout<<s<<" -> " << *i << '\n';
visited[*i] = true;
queue.push_back(*i);
}
}
}
delete [] visited;
}
as you can see it directly jumped to 23 somehow, despite not visiting it until after 22. The problem statement says to sort the neighbors by increasing ID but this didn't work either. Any insight?