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 distance(int a, int b) to the class. When called on an unweighted graph, the function should return the distance from node a to node b, that is, the length of the shortest path between node a and b. If there is no path, the function should return -1.
All the input graphs will be simple (no self-loops or parallel edges) and unweighted, but they can directed or undirected. It is guaranteed that |V|≤100, |E|≤500 and that the function will be called with valid nodes (i.e., 1≤a,b≤|V|)
You should submit the file graph.h with the method distance 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() { // Read one input graph Graph *g = Graph::readGraph(); // read q pairs of integers to indicate the queries int q; std::cin >> q; for (int i=0; i<q; i++) { int a, b; std::cin >> a >> b; std::cout << "g->distance(" << a << "," << b << ") = " << g->distance(a,b) << std::endl; } delete g; return 0; }
Example Input 1 | Example Output 1 |
9 undirected unweighted 9 1 2 1 3 4 2 4 3 4 5 5 6 5 7 6 9 7 8 7 1 2 1 4 1 5 1 6 1 8 4 9 8 3 |
g->distance(1,2) = 1 g->distance(1,4) = 2 g->distance(1,5) = 3 g->distance(1,6) = 4 g->distance(1,8) = 5 g->distance(4,9) = 3 g->distance(8,3) = 4 |
Explanation of Example Input 1
The graph of the example input 1 corresponds to the following figure:
Example Input 2 | Example Output 2 |
8 directed unweighted 8 1 3 2 1 4 2 5 4 5 6 6 7 6 8 8 7 5 5 3 3 5 5 8 6 7 7 7 |
g->distance(5,3) = 4 g->distance(3,5) = -1 g->distance(5,8) = 2 g->distance(6,7) = 1 g->distance(7,7) = 0 |
Explanation of Example Input 2
The graph of the example input 2 corresponds to the following figure: