Topological sort/Backtracking