Code:

get_order(first_vertex, vertices_to_consider): /* Define some variables */ order = [] stack = empty_stack cur_dfsnum = 0 index = [] low = [] /* Nested function, has access to above variables (closure) */ visit(cur_vertex): index[cur_vertex] = cur_dfsnum low[cur_vertex] = cur_dfsnum cur_dfsnum++ push cur_vertex on stack for each child in cur_vertex.edges where child in vertices_to_consider if index[child] == "To be done" visit(child) low[cur_vertex] = min(low[cur_vertex], low[child]) else if index[child] == "Done" /* Do nothing */ else low[cur_vertex] = min(low[cur_vertex], index[child]) if low[cur_vertex] == index[cur_vertex] /* we found an SCC */ scc = [] do popped = pop from stack scc += popped index[popped] = "Done" until popped == current_vertex if scc.length == 1 order = cur_vertex + order else order = get_order(choose_first(scc), scc) + order /* visit() ends */ for vertex in vertices_to_consider: index[vertex] = "To be done" /* Special-case the start vertex to prevent infinite recursion */ index[first_vertex] = "Done" for each child in first_vertex.edges where child in vertices_to_consider if index[child] == "To be done" visit(child) order = first_vertex + order return order