#include <iostream>
#include <vector>
#include <map>
#include <stack>
#include <queue>
using namespace std;
// [('A','B'),('A','C'),('A','E'),('B','D'), ('B','F'), ('C','G'),('E','F')]
// [(0,1),(0,2),(0,4),(1,3),(1,5),(2,6),(4,5)]
// rudimentary graph using adjacency lists
map<int, vector<int> > graph{{0, {1,2,4}}, {1, {0,3,5}}, {2,{0,6}},{3,{1}},{4,{0,5}},{5,{1,4}},{6,{2}}};
graph
{ 0 => { 1, 2, 4 }, 1 => { 0, 3, 5 }, 2 => { 0, 6 }, 3 => { 1 }, 4 => { 0, 5 }, 5 => { 1, 4 }, 6 => { 2 } }
template <typename GRAPH>
void innerDFS(GRAPH g, int v, vector<bool> & visited) {
cout << " " << v << " ";
visited[v] = true;
// for each vertex adjacent to v
for (auto w : g[v]) {
if (! visited[w]) {
innerDFS(g, w, visited);
}
}
}
template <typename GRAPH>
void DFS(GRAPH g)
{
vector<bool> visited(g.size(), false); // track visited nodes
for (auto kvpair : g) {
int v = kvpair.first;
if (! visited[v])
innerDFS(g, v, visited);
}
}
DFS(graph)
0 1 3 5 4 2 6
template <typename GRAPH>
void DFSStack(GRAPH g)
{
stack<int> s;
vector<bool> visited(g.size(), false);
int v = g.begin()->first;
cout << " " << v << " ";
visited[v] = true;
s.push(v);
while (!s.empty()) {
v = s.top();
bool hasAdjacent = false;
for (auto w: g[v])
if (! visited[w]) {
cout << " " << w << " ";
visited[w] = true;
s.push(w);
hasAdjacent = true;
break;
}
if (! hasAdjacent)
s.pop();
}
}
DFSStack(graph)
0 1 3 5 4 2 6
template <typename GRAPH>
void BFS(GRAPH g)
{
queue<int> q;
vector<bool> visited(g.size(), false);
int v = g.begin()->first;
cout << " " << v << " ";
visited[v] = true;
q.push(v);
while (!q.empty()) {
v = q.front();
q.pop();
for (auto w: g[v])
if (! visited[w]) {
cout << " " << w << " ";
visited[w] = true;
q.push(w);
}
}
}
BFS(graph)
0 1 2 4 3 5 6