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]
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 bool hasCycle() to the class. If called on a directed graph, the function should return true of the graph has at least one cycle or false otherwise. A cycle is a path that starts and ends on the same node.
All the input graphs will be simple (no self-loops or parallel edges), unweighted and directed. It is guaranteed that |V|<=100 and |E|<=500.
You should submit the file graph.h with the method hasCycle 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 <list> #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 << ": hasCycle() = " << (g->hasCycle()?"true":"false") << std::endl; delete g; } return 0; }
Example Input | Example Output |
4 9 directed unweighted 9 1 2 1 3 2 4 3 4 4 5 5 6 7 5 9 6 8 7 8 directed unweighted 8 3 1 1 2 2 4 5 4 4 6 6 7 6 8 8 7 4 directed unweighted 4 1 2 3 1 2 4 4 3 4 directed unweighted 6 1 2 2 1 1 3 3 1 2 3 3 2 |
Graph #1: hasCycle() = false Graph #2: hasCycle() = false Graph #3: hasCycle() = true Graph #4: hasCycle() = true |
Explanation of Example Input
The first graph of the example input corresponds to the following figure:
(it does not have any cycles):
The second graph of the example input corresponds to the following figure:
(it does not have any cycles):
The third graph of the example input corresponds to the following figure:
(it has a cycle: 1→2→4→3→1)
The fourth graph of the example input corresponds to the following figure:
(it has several cycles such as 1→2→1 or 1→2→3→1)