Updating topological sort algorithm to avoid stack overflow