|
|
|
|
|
by kps
1148 days ago
|
|
Detecting a cycle in a directed graph is useful (in certain domains I've worked in), but doesn't have a cute trick answer. [Edit: I in mind ‘Detecting the cycles’ rather than ‘Detecting a cycle’ but wrote the wrong thing. Mea culpa.] Your actual job will be more like implementing a maximally performant directed graph in safe Rust. (Not really. It won't be that interesting.) |
|
Doesn't the standard cute trick answer for a linked list (tortoise and hare) work fine? Do two parallel breadth-first traversals of the graph starting at the root node, one at twice the speed of the other. (If there's multiple root nodes, introduce a unique super-root that points to the roots.) If there's at least one cyclic path, both iterations will enter the same cyclic path because iteration order is the same, at which point it reduces to the linked list problem.