In what concerns the continuous evaluation solving exercises grade during the semester, you should submit until 23:59 of December 14th
(this exercise will still be available for submission after that deadline, but without couting towards your grade)
[to understand the context of this problem, you should read the class #09 exercise sheet]


[AED051] Number of Connected Components

In this problem you should only submit a graph.h file with a self-containing definition of a class Graph.

Base Code

Use as a basis the class Graph (see code | download code) which implements a graph (that can have directions and weights) using an adjacency list, assumes nodes are identified by integers between 1 and |V| and already has methods for adding an edge, reading a graph and doing a basic DFS and a basic BFS.

The Problem

Add a new method int nrConnectedComponents() to the class. If called on an undirected graph, the function should return the number of connected components of the graph. A connected component of an undirected graph is a connected subgraph that is not part of any larger connected subgraph. A connected subgraph is a set of vertices in the graph that are linked to each other by paths.

All the input graphs will be simple (no self-loops or parallel edges), unweighted and undirected. It is guaranteed that |V|<=100 and |E|<=500.

Submission

You should submit the file graph.h with the method nrConnectedComponents added to Graph as requested (and without removing any of the other existing methods). You can however create additional methods and/or attribute variables, if you need them.

Mooshak will use the following code to link to your class, read the inputs, build the graphs and call your method, printing its result.

#include <iostream>
#include "graph.h"

int main() {

  // Number of graphs to test
  int n;
  std::cin >> n;

  // For each graph: read, call the method and delete graph at the end
  for (int i=1; i<=n; i++) {
    Graph *g = Graph::readGraph(); 
    std::cout << "Graph #" << i << ": nrConnectedComponents() = " << g->nrConnectedComponents() << std::endl;
    delete g;
  }
    
  return 0;
}

Example Input Example Output
2

9 undirected unweighted
7
1 2
1 3
2 3
4 5
6 9
7 6
7 8

12 undirected unweighted
15
1 2
2 3
3 4
5 6
1 8
2 8
3 8
5 11
5 12
6 11
6 12
7 8
9 8
10 11
12 11
Graph #1: nrConnectedComponents() = 3
Graph #2: nrConnectedComponents() = 2

Explanation of Example Input

The first graph of the example input corresponds to the following figure:

It has 3 components indicated in different colors: {1,2,3}, {4,5} and {6,7,8,9}.

The second graph of the example input corresponds to the following figure:

It has 2 components indicated in different colors: {1,2,3,4,7,8,9} and {5,6,10,11,12}.



Algorithms and Data Structures (L.EIC011) 2024/2025
DCC/FCUP & DEI/FEUP - University of Porto