// do a DFS traversal from all nodes // // nodes = list of all nodes from G // adj[node] = the adjacency list of node // example: adj[node] = {..., neigh, ...} => edge (node, neigh) // DFS(G=(nodes, adj)) { // STEP 0: initialize results // p[node] = parent of node in the BFS traversal started from source // start[node] = the timestamp (the order) when we started visiting the node subtree // finish[node] = the timestamp (the order) when we finished visiting the node subtree // [optional] color[node] = white/gray/black // * white = not yet visited // * gray = visit in progress // * black = visited foreach (node in nodes) { p[node] = null; // parent not yet found // [optional] color[node] = white; } timestamp = 0; // the first timestamp before the DFS traversal foreach (node in nodes) { if (p[node] == null) { // or [optional] color[node] == white DFS_RECURSIVE(node, G, p, timestamp) } } } DFS_RECURSIVE(node, G=(node, adj), p, ref timestamp) { start[node] = ++timestamp; // start visiting its subtree // [optional] color[node] = gray; for (neigh in adj[node]) { // for each neighbour if (p[neigh] == null) { // or [optional] color[neigh] = white; p[neigh] = node; // save parent DFS_RECURSIVE(neigh, G, p, timestamp); // continue traversal } } finish[node] = ++timestamp; // finish visiting its subtree // [optional] color[node] = black; }