THINK FIRST·CODE LATER

← All labs

Finding a cycle in a directed graph with DFS colours

Problem

Tasks depend on each other: an edge u v means "u must be done before v". Write CycleFinder. Read n m and m directed edges. Run DFS from vertices 0, 1, 2, … visiting neighbours in increasing order, with three colours: white (unvisited), gray (on the current path), black (finished).

  • An edge to a gray vertex closes a cycle: print it (from that vertex back to itself, following the DFS path) and No valid order exists.
  • If there is no cycle, print No cycle (the graph is a DAG) and a topological order (reverse order of finishing).

For the input

5 5
0 1
1 2
2 3
3 1
0 4

the program prints

Cycle found: 1 -> 2 -> 3 -> 1
No valid order exists

A DAG usually has several valid orders, so for acyclic graphs the tests check only the first line.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d15-4-data-1.txt

5 5
0 1
1 2
2 3
3 1
0 4
What your program must print for d15-4-data-1.txt
Cycle found: 1 -> 2 -> 3 -> 1
No valid order exists

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d15-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content d15-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.