flowchart TD
A[Build graph and indegree] --> B[Queue indegree 0 nodes]
B --> C{Queue empty}
C -- No --> D[Pop node append order]
D --> E[Decrease neighbors indegree]
E --> F{Neighbor indegree 0}
F -- Yes --> G[Enqueue neighbor]
F -- No --> H[Continue]
G --> C
H --> C
C -- Yes --> I{order size n}
I -- Yes --> J[Valid topological order]
I -- No --> K[Cycle detected]
sequenceDiagram
participant Q as queue
participant In as indegree[]
participant G as graph
Q->>Q: pop zero indegree
Q->>G: visit outgoing edges
G->>In: decrement neighbor indegree
In-->>Q: enqueue newly zero nodes