From e5d667142607bf7b4e8b2701d6516c7091cd8e13 Mon Sep 17 00:00:00 2001 From: aalbaali Date: Sun, 18 Jun 2023 16:06:20 -0400 Subject: [PATCH] Use stack instead of vector in DFS Signed-off-by: aalbaali --- include/transforms_graph/graph_search.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/include/transforms_graph/graph_search.h b/include/transforms_graph/graph_search.h index 8c969d4..ece14b3 100644 --- a/include/transforms_graph/graph_search.h +++ b/include/transforms_graph/graph_search.h @@ -13,6 +13,7 @@ #include #include #include +#include namespace tg { /** @@ -29,13 +30,13 @@ std::vector DFS(const Graph& graph, Node start, Node end) { std::vector path; std::unordered_set visited; std::unordered_map parent; - std::vector stack; + std::stack stack; bool found_solution = false; - stack.push_back(start); + stack.push(start); while (!stack.empty()) { - Node current = stack.back(); - stack.pop_back(); + Node current = stack.top(); + stack.pop(); // Found the end if (current == end) { @@ -47,7 +48,7 @@ std::vector DFS(const Graph& graph, Node start, Node end) { for (const auto& neighbour : graph.at(current)) { if (visited.count(neighbour)) continue; - stack.push_back(neighbour); + stack.push(neighbour); parent[neighbour] = current; } }