#include #include #include #include #define inf (std::numeric_limits::max()) enum Color { WHITE, GRAY, BLACK }; typedef int Node; typedef std::vector> List; typedef std::vector Colors; int t = 0; void dfs_visit(const List& neighbours, Colors& color, std::vector& d, std::vector& f, std::vector& pi, int u) { t++; d[u] = t; color[u] = GRAY; for (Node v : neighbours[u]) { if (color[v] == WHITE) { pi[v] = u; dfs_visit(neighbours, color, d, f, pi, v); } } color[u] = BLACK; t++; f[u] = t; } void dfs(const List& neighbours, Colors& color, std::vector& d, std::vector& f, std::vector& pi) { const int n = neighbours.size(); for (Node u = 0; u < n; u++) { color[u] = WHITE; pi[u] = -1; } t = 0; for (Node u = 0; u < n; u++) { if (color[u] == WHITE) { dfs_visit(neighbours, color, pi, d, f, u); } } } void print_path(const std::vector& pi, Node s, Node v) { if (v == s) { std::cout << s << std::endl; } else if (pi[v] == -1) { std::cout << "No path from " << s << " to " << v << "!" << std::endl; exit(EXIT_FAILURE); } else { print_path(pi, s, pi[v]); std::cout << v << std::endl; } } int main(int argc, const char *argv[]) { List neighbours = { {1, 3}, {0, 4}, {4, 5}, {0}, {1, 2, 5}, {2, 4} }; const int n = neighbours.size(); Colors colors(n); std::vector d(n); std::vector f(n); std::vector pi(n); dfs_visit(neighbours, colors, d, f, pi, 0); print_path(pi, 0, 4); return 0; }