In a directed graph, adding an edge from A → B creates a cycle if and only if B can already reach A.
"You’re not just looking for a loop," Kai said. "You’re looking for a chain . Before you lock a new edge from winner to loser , ask yourself: is there any path from the loser back to the winner using the edges already locked? If yes, this new edge would complete the cycle. Skip it." Cs50 Tideman Solution
Maya pointed. "I wrote a recursive function creates_cycle(winner, loser) . It checks if the loser has any locked edges pointing to another candidate. Then it checks if that candidate points back to the original winner. If yes, it’s a cycle." In a directed graph, adding an edge from
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." Before you lock a new edge from winner
Every year, the village of Coderidge held an election for the Keeper of the Orchard. Unlike other villages, they used a complex ranked voting system designed by a long-dead mathematician named Tideman. The rule was simple: if there was a way to trace a circle of preference (A beats B, B beats C, C beats A), that circle was a paradox, and the weakest link in that circle must be ignored.
"Yes," Maya sighed. "I sort the pairs. Strongest first. Alice over Bob? Lock it. Bob over Charlie? Lock it. Charlie over Alice? Don't lock it because it creates a cycle. But my cycle detection is wrong."