//
// Created by YUQIONG LI on 16/9/2018.
//
#include <iostream>
#include <map>
#include <vector>
#include <stack>
using std::cout;
using std::map;
using std::vector;
using std::endl;
using std::stack;
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(){
map<int, vector<int> > m = makeGraph();
vector<int> visited;
stack<int> s;
s.push(0);
while(!s.empty()){
int curr = s.top();
if (std::find(visited.begin(), visited.end(), curr) != visited.end()){
// already visited
s.pop();
continue;
}
cout << curr << ' ';
s.pop();
visited.push_back(curr);
for (auto & neighbors: m[curr]){
s.push(neighbors);
}
}
cout << endl;
return 0;
}
180916 pre-order : simple version.
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.