How would you implement a function to detect cycles in a graph representing a network of industrial machines, and how would you optimize it?