Trying to implement Depth First Search. Implemented adjacency list using vector. Keeping track of vertices that have been explored by set "explored". "s" is the starting vertex. I think the problem is in while loop but can't figure out.
void AddEdge(vector<vector<int>>& adjList, int u, int v) {
adjList[u].push_back(v);
adjList[v].push_back(u);
}
void dfs(vector<vector<int>>& adjList, int s) {
stack<int> adjacent;
set<int> explored;
adjacent.push(s);
while(adjacent.size() != 0) {
int vertex = adjacent.top();
adjacent.pop();
if(explored.count(vertex) == 0)
explored.insert(vertex);
for(vector<int>::iterator itr = adjList[vertex].begin();
itr != adjList[vertex].end(); ++itr) {
adjacent.push(*itr);
}
}
for(set<int>::iterator itr = explored.begin(); itr != explored.end();
++itr) {
cout << "vertices reachable from " << s << " are " << "--> " << *
(itr);
}
}
Thanks in advance.