THINK FIRST·CODE LATER

← All labs

Connected components

Problem

Write Components. Read an undirected graph: n m, then m edges u v (vertices 0 … n − 1), then pairs a b to test. Using BFS (or DFS) from every not-yet-visited vertex in increasing order, label each vertex with its component. Print each component (vertices sorted), the number of components and the size of the largest, whether the graph is connected, how many edges would be needed to connect everything, and for each pair whether the two vertices are connected.

For the input

8 5
0 1
1 2
3 4
5 6
6 5
0 2 3 5 7 7

the program prints

Component 1: [0, 1, 2]
Component 2: [3, 4]
Component 3: [5, 6]
Component 4: [7]
Components: 4, largest has 3 vertices
Connected graph: false
Edges needed to connect everything: 3
0 and 2 connected: true
3 and 5 connected: false
7 and 7 connected: true

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-3-data-1.txt

8 5
0 1
1 2
3 4
5 6
6 5
0 2 3 5 7 7
What your program must print for d15-3-data-1.txt
Component 1: [0, 1, 2]
Component 2: [3, 4]
Component 3: [5, 6]
Component 4: [7]
Components: 4, largest has 3 vertices
Connected graph: false
Edges needed to connect everything: 3
0 and 2 connected: true
3 and 5 connected: false
7 and 7 connected: true

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-3-data-1.txt

Windows PowerShell does not understand <:

Get-Content d15-3-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.