topological sort, detect cycle