package java_programs;
import java.util.*;

public class DEPTH_FIRST_SEARCH {
    public static boolean depth_first_search(Node startNode, Node goalNode) {
        Set<Node> nodesVisited = new HashSet<>();
        return new Search(nodesVisited, goalNode).search(startNode);
    }

    static class Search {
        private Set<Node> nodesVisited;
        private Node goalNode;

        public Search(Set<Node> nodesVisited, Node goalNode) {
            this.nodesVisited = nodesVisited;
            this.goalNode = goalNode;
        }

        public boolean search(Node currentNode) {
            if (currentNode == null) {
                return false;
            }
            if (currentNode.equals(goalNode)) {
                return true;
            }
            if (!nodesVisited.add(currentNode)) { // This checks and marks the node as visited
                return false; // returns false if already visited
            }
            for (Node successor : currentNode.getSuccessors()) {
                if (search(successor)) {
                    return true;
                }
            }
            return false; // returns false if no unvisited successors lead to the goal
        }
    }
}