TheAlgorithms-C-Plus-Plus/graph/DFS_with_stack.cc

58 lines
994 B
C++
Raw Normal View History

2017-10-01 15:40:00 +08:00
#include <iostream>
#include <list>
#include <stack>
#define WHITE 0
#define GREY 1
#define BLACK 2
#define INF 99999
using namespace std;
int checked[999] = {WHITE};
2019-08-21 10:10:08 +08:00
void dfs(const list<int> lista[], int start)
{
2017-10-01 15:40:00 +08:00
stack<int> stack;
int checked[999] = {WHITE};
2019-08-21 10:10:08 +08:00
2017-10-01 15:40:00 +08:00
stack.push(start);
2019-08-21 10:10:08 +08:00
2017-10-01 15:40:00 +08:00
checked[start] = GREY;
2019-08-21 10:10:08 +08:00
while (!stack.empty())
{
2017-10-01 15:40:00 +08:00
int act = stack.top();
stack.pop();
2019-08-21 10:10:08 +08:00
if (checked[act] == GREY)
{
2017-10-01 15:40:00 +08:00
cout << act << ' ';
2019-08-21 10:10:08 +08:00
for (auto it = lista[act].begin(); it != lista[act].end(); ++it)
{
2017-10-01 15:40:00 +08:00
stack.push(*it);
2019-08-21 10:10:08 +08:00
if (checked[*it] != BLACK)
2017-10-01 15:40:00 +08:00
checked[*it] = GREY;
}
checked[act] = BLACK; //nodo controllato
}
}
}
2019-08-21 10:10:08 +08:00
int main()
{
int u, w;
int n;
cin >> n;
list<int> lista[INF];
for (int i = 0; i < n; ++i)
{
cin >> u >> w;
lista[u].push_back(w);
}
2017-10-01 15:40:00 +08:00
2019-08-21 10:10:08 +08:00
dfs(lista, 0);
2017-10-01 15:40:00 +08:00
2019-08-21 10:10:08 +08:00
return 0;
2017-10-01 15:40:00 +08:00
}