Cycles in undirected graphs · Compiler
Cycles in undirected graphs
Start with n isolated vertices and add the two-way links in input order. Find the first addition that closes a cycle, meaning its endpoints were already connected by a path before that link was added.
- Input
- The first line contains n m. Vertices are numbered 0 through n-1 (1 <= n <= 50, 0 <= m <= 200). Each of the next m lines contains u v for an edge joining u and v in both directions. Endpoints differ and each unordered pair occurs at most once.
- Output
- Print the 1-based number of the first such addition, or 0 if every addition keeps the graph acyclic.
Compiler Explorer runs your code when you run or check it.
Loading your exercise draft…