Fix bug that topological-sort did not detect cycle

The previous implementation of cycle detection does not always work because
there's at least one node with no incoming edge does not mean that there's
no cycle in the graph.