BFS of graph

#include <iostream> #include <map> #include <vector> #include <queue> using std::cout; using std::map; using std::vector; using std::endl; using std::queue; /* * BFS traversal of a graph */ map< int, vector<int> > makeGraph(){ map<int, vector<int> > m; m[0] = {1, 3}; m[1] = {3, 0, 1}; m[2] = {2}; m[3] = {0}; return m; }; int main() { // construct graph map<int, vector<int> > m = makeGraph(); vector<int> visited; // all the nodes that are visited queue<int> tovisit; tovisit.push(0); while (!tovisit.empty()){ int curr = tovisit.front(); tovisit.pop(); if (std::find(visited.begin(), visited.end(), curr) != visited.end()){ // current element already visited continue; } // else, current element has not been visited // first put all its neighbors in the to-visit list for (auto & neighbor: m[curr]){ tovisit.push(neighbor); } // visit this node cout << curr << ' '; visited.push_back(curr); } cout << endl; return 0; }
20180916

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.