Graphs · Exercise 42 of 100

Cycles in undirected graphs

In a simple undirected graph, a cycle is a loop that returns to its starting vertex without reusing an edge or repeating an intermediate vertex. When adding a new edge between distinct vertices, check whether a path already joins its endpoints. If so, that path and the new edge form a cycle.

Try it yourself

Add the undirected edges AB, CD, BC and DA in that order to four isolated vertices. Number the additions from 1 to 4. What is the number of the first addition that creates a cycle?

One-step hint

Before drawing each new edge, see whether you can already trace a path between its endpoints using only the edges drawn so far.

Worked solution
  1. AB and CD make two separate pairs. BC joins them into the single path A to B to C to D.
  2. Addition 4 joins D back to A, closing a loop along the existing path.
DSA compiler