Cs50 Tideman Solution ✧

In a directed graph, adding an edge from A → B creates a cycle if and only if B can already reach A.

"It's not about the edge you're adding," she whispered. "It's about the path that already exists beneath it." Cs50 Tideman Solution

The story is useful because the narrative (the cycle, the DFS, the "path back") sticks in your brain longer than any pseudocode. Next time you face Tideman, remember Maya and the Orchard. In a directed graph, adding an edge from

// 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; } Next time you face Tideman, remember Maya and the Orchard

Maya was the new programmer tasked with tabulating the votes. She had the first part down: counting each ballot to build a 2D array of preferences . It told her that Alice beat Bob (5 votes to 2), Bob beat Charlie (4 to 3), and Charlie beat Alice (3 to 2). A perfect, frustrating cycle.

Maya ran check50 . Green smiles across the board. She leaned back.

Cs50 Tideman Solution
Закрыть
Перейти