-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDepthFirstSearch.cpp
More file actions
65 lines (53 loc) · 2.06 KB
/
DepthFirstSearch.cpp
File metadata and controls
65 lines (53 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "DepthFirstSearch.h"
#include <vector>
#include <stack>
#include <unordered_map>
#include <unordered_set>
using namespace std;
vector<string> depthFirstSearch(const CityGraph& graph, const string& start, const string& goal, double& totalDistance) {
stack<string> stack;
unordered_map<string, string> cameFrom; // For path reconstruction
unordered_map<string, double> distanceFromStart;
unordered_set<string> visited; // Tracks visited nodes
totalDistance = 0.0;
// Initialize DFS
stack.push(start);
cameFrom[start] = "";
distanceFromStart[start] = 0.0;
//DFS Algorithm
while (!stack.empty()) {
string current = stack.top();
stack.pop();
// Mark as visited
visited.insert(current);
// Goal check
if (current == goal) {
vector<string> path;
string at = goal;
// Reconstruct path and calculate total distance using the enhanced snippet
while (at != "") {
path.push_back(at);
string predecessor = cameFrom[at];
// Ensure valid graph access and calculate distance
if (predecessor != "" && predecessor != start) {
if (graph.find(at) != graph.end() && graph.find(predecessor) != graph.end()) {
totalDistance += graph.at(at).distanceTo(graph.at(predecessor));
}
}
at = predecessor; // Move to the predecessor for the next iteration
}
reverse(path.begin(), path.end());
return path; // Return the path found
}
// Explore neighbors
for (const string& next : graph.at(current).adjacents) {
if (visited.find(next) == visited.end()) {
stack.push(next);
if (cameFrom.find(next) == cameFrom.end()) { // Avoid overwriting cameFrom if already set
cameFrom[next] = current;
}
}
}
}
return {}; // Return empty path if goal is not reachable
}