indegree
to store the number of incoming edges for each node.adj
to store outgoing edges from each node.indegree
and adj
using the prerequisites
array.q
and add all nodes with an indegree of zero.nodesVisited
to count the number of processed nodes.q
is not empty:
a. Dequeue a node from q
and increment nodesVisited
.
b. For each neighbor of the dequeued node, decrement its indegree.
c. If a neighbor's indegree becomes zero, enqueue it.true
if nodesVisited
equals numCourses
, indicating no cycle; otherwise, return false
.