In what concerns the continuous evaluation solving exercises grade during the semester, you should submit until 23:59 of December 21st
(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 #10 exercise sheet]
In this problem you should only submit a graph.h file with a self-containing definition of a class Graph.
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.
Add a new method int diameter() to the class. When called on an unweighted and undirected graph, the function should return the diameter of the graph, that is, the maximum length of a shortest path between a pair of nodes of the graph. If there is more than one connected component, the function should return -1.
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.
You should submit the file graph.h with the method diameter 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 << ": diameter() = " << g->diameter() << std::endl; delete g; } return 0; }
Example Input | Example Output |
3 9 undirected unweighted 9 1 2 1 3 4 2 4 3 4 5 5 6 5 7 6 9 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 8 9 10 11 11 12 10 undirected unweighted 12 1 2 2 3 3 4 4 5 1 6 2 6 4 10 5 10 6 7 7 8 8 9 9 10 |
Graph #1: diameter() = 5 Graph #2: diameter() = -1 Graph #3: diameter() = 4 |
Explanation of Example Input
The first graph of the example input corresponds to the following figure:
Its diameter is 5 (which is the maximum distance between any two nodes, such as between 1 and 9)
The second graph of the example input corresponds to the following figure:
Since the graph is not connected (it has two connected components) the answer is -1.
The third graph of the example input corresponds to the following figure:
Its diameter is 4 (which is the maximum distance between any two nodes, such as between 1 and 5)