Skip to content

Commit

Permalink
Use stack instead of vector in DFS
Browse files Browse the repository at this point in the history
Signed-off-by: aalbaali <[email protected]>
  • Loading branch information
aalbaali committed Jun 18, 2023
1 parent 8e0f35b commit e5d6671
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions include/transforms_graph/graph_search.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <stack>

namespace tg {
/**
Expand All @@ -29,13 +30,13 @@ std::vector<Node> DFS(const Graph& graph, Node start, Node end) {
std::vector<Node> path;
std::unordered_set<Node> visited;
std::unordered_map<Node, Node> parent;
std::vector<Node> stack;
std::stack<Node> 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) {
Expand All @@ -47,7 +48,7 @@ std::vector<Node> 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;
}
}
Expand Down

0 comments on commit e5d6671

Please sign in to comment.