Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class PathNode {
- private:
- FVector Position;
- PathNode* CameFrom;
- public:
- // Constructor
- PathNode(const FVector& pos, PathNode* cameFrom = nullptr)
- : Position(pos), CameFrom(cameFrom) {}
- // Getters
- FVector getPosition() const { return Position; }
- PathNode* getCameFrom() const { return CameFrom; }
- // Operator to compare nodes based on position
- bool operator==(const PathNode& other) const {
- return Position == other.Position;
- }
- };
- TArray<FVector> UDungeonGeneratorAPI::FindPathDFS(const FVector& start, const FVector& end)
- {
- std::stack<PathNode*> stack;
- std::vector<PathNode*> visited;
- stack.push(new PathNode(start));
- auto IsVisited = [&visited](const FVector& pos) {
- return std::any_of(visited.begin(), visited.end(), [&pos](const PathNode* n) {
- return n->getPosition() == pos;
- });
- };
- while (!stack.empty()) {
- PathNode* currentNode = stack.top();
- stack.pop();
- if (currentNode->getPosition() == end) {
- // Construct the path by tracing back from the end node to the start node
- TArray<FVector> path;
- while (currentNode != nullptr) {
- path.Add(currentNode->getPosition());
- currentNode = currentNode->getCameFrom();
- }
- std::reverse(path.begin(), path.end());
- // Clean up memory used by nodes
- for (auto node : visited) delete node;
- delete currentNode;
- while (!stack.empty()) {
- delete stack.top();
- stack.pop();
- }
- return path;
- }
- if (!IsVisited(currentNode->getPosition())) {
- visited.push_back(currentNode);
- // Explore neighbors
- for (auto& dir : { FVector(1, 0, 0), FVector(-1, 0, 0), FVector(0, 1, 0), FVector(0, -1, 0) }) {
- FVector neighborPos = currentNode->getPosition() + dir * tileSize;
- if (!IsVisited(neighborPos)) {
- stack.push(new PathNode(neighborPos, currentNode));
- }
- }
- }
- }
- // Clean up memory if no path found
- for (auto node : visited) delete node;
- while (!stack.empty()) {
- delete stack.top();
- stack.pop();
- }
- return {};
- }
Add Comment
Please, Sign In to add comment