Skip to content

Commit e5d6671

Browse files
committed
Use stack instead of vector in DFS
Signed-off-by: aalbaali <albaalia@live.com>
1 parent 8e0f35b commit e5d6671

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

include/transforms_graph/graph_search.h

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#include <unordered_map>
1414
#include <unordered_set>
1515
#include <vector>
16+
#include <stack>
1617

1718
namespace tg {
1819
/**
@@ -29,13 +30,13 @@ std::vector<Node> DFS(const Graph& graph, Node start, Node end) {
2930
std::vector<Node> path;
3031
std::unordered_set<Node> visited;
3132
std::unordered_map<Node, Node> parent;
32-
std::vector<Node> stack;
33+
std::stack<Node> stack;
3334

3435
bool found_solution = false;
35-
stack.push_back(start);
36+
stack.push(start);
3637
while (!stack.empty()) {
37-
Node current = stack.back();
38-
stack.pop_back();
38+
Node current = stack.top();
39+
stack.pop();
3940

4041
// Found the end
4142
if (current == end) {
@@ -47,7 +48,7 @@ std::vector<Node> DFS(const Graph& graph, Node start, Node end) {
4748

4849
for (const auto& neighbour : graph.at(current)) {
4950
if (visited.count(neighbour)) continue;
50-
stack.push_back(neighbour);
51+
stack.push(neighbour);
5152
parent[neighbour] = current;
5253
}
5354
}

0 commit comments

Comments
 (0)