From 17c39e2798c51eb5e8b06a98c8c94a0e65e9f7aa Mon Sep 17 00:00:00 2001 From: Amrita Goswami Date: Mon, 27 May 2024 11:36:43 +0000 Subject: [PATCH] network_operations: Graph traversal methods Added a class to handle traversing a network, using a simple DFS. TODO: add functions to handle shortest paths. --- graph_lib/include/network_operations.hpp | 41 +++++++++++++++++++----- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/graph_lib/include/network_operations.hpp b/graph_lib/include/network_operations.hpp index ed07b6c..afa1b8f 100644 --- a/graph_lib/include/network_operations.hpp +++ b/graph_lib/include/network_operations.hpp @@ -14,20 +14,42 @@ template class NetworkOperations { NetworkOperations(NetworkBase network) : network(network), marked(std::vector(network.n_agents(), false)), - count(0) {} + count(0), edge_to_vertex(std::vector(network.n_agents())) {} + + // Returns a path from a source s to a vertex v using DFS (if it exists) + // If it does not exist, return nullopt + // This will not give all the paths (or even the shortest path) + std::optional> path_from_dfs(size_t s, size_t v) { + std::vector path{}; // Path from s to v + reset_variables_counters(); // Reset marked and count + // DFS starting from the source + dfs(s); + if (!path_exists_to_vertex(v)) { + return std::nullopt; // the path does not exist + } + // If the path exists, return it + for (int x = v; x != s; x = edge_to_vertex[x]) { + path.push_back(x); + } + return path; + } private: - NetworkBase network; // UndirectedNetwork or DirectedNetwork + NetworkBase network{}; // UndirectedNetwork or DirectedNetwork std::vector - marked; // Chronicles whether a vertex has been visited or not - size_t count; // Number of vertices visited + marked{}; // Chronicles whether a vertex has been visited or not + size_t count{}; // Number of vertices visited + std::vector + edge_to_vertex{}; // Last vertex on known path, to a vertex + // (given by the index in this vector) // Depth first search from vertex v - void dfs(int v) { - count++; + void dfs(size_t v) { + count++; // Update the number of vertices visited marked[v] = true; - for (int w : network.get_neighbours(v)) { + for (size_t w : network.get_neighbours(v)) { if (!marked[w]) { + edge_to_vertex[w] = v; dfs(w); } } @@ -35,9 +57,12 @@ template class NetworkOperations { // Reset marked (that chronicles visited vertices) and count (number of // vertices visited) - void reset_counters() { + void reset_variables_counters() { count = 0; marked.resize(network.n_agents(), false); } + + // Returns false if a path to vertex v does not exist + bool path_exists_to_vertex(size_t v) { return marked[v]; } }; } // namespace Graph