cycle detection with dijkstra's algorithm