// Returns true if adding edge winner->loser creates a cycle bool creates_cycle(int winner, int loser) { // If the loser can reach the winner through existing locked edges, // then adding winner->loser would complete a cycle. return dfs(loser, winner); } bool dfs(int current, int target) { if (current == target) return true; for (int i = 0; i < candidate_count; i++) { if (locked[current][i] && dfs(i, target)) return true; } return false; }
Kai nodded slowly. "You are looking for a direct path back to the winner. But what if the path is three steps? Four? Your recursion only goes two levels deep." Cs50 Tideman Solution
Maya’s heart sank. She had been checking loser → X → winner . But what about loser → X → Y → winner ? // Returns true if adding edge winner->loser creates
"It's not about the edge you're adding," she whispered. "It's about the path that already exists beneath it." But what if the path is three steps