Search code examples
javaalgorithmartificial-intelligencedepth-first-search

Depth First Search algorithm with target node


I have to use DFS algorithm for my university project. I saw this link DFS but i face this problem. The Depth First Search algorithm is Traversal it goes to every node in the graph but i want to define a target node when i reach to it i want to stop the algorithm i tried the following code but it still go to all node

void DFSUtil(int v, int goal, boolean visited[]) {
            visited[v] = true;

            Iterator<Integer> i = adj[v].listIterator();

            while (i.hasNext()) {
                int n = i.next();
                if (!visited[n]) {
                    if (n == goal) {
                        System.err.print(infoLinkedList.get(1).nameStation+":");
                        System.err.print(" |"+goal+ "| -> ");
                        return;
                    }
                }
            }
    }

Solution

  • Your algorithm is not DFS, it visits the neighbours of the node v and that's it. A DFS would look something like this:

    void DFSUtil(int v, int goal, boolean visited[]) {
            Stack<Integer> stack = new Stack<>();
            stack.add(v);
    
            while (!stack.isEmpty()) {
                var n = stack.pop();
                if (!visited[n]) {
                    if (n == goal) {
                        System.err.print(infoLinkedList.get(1).nameStation + ":");
                        System.err.print(" |" + goal + "| -> ");
                        return;
                    }
                    visited[n] = true;
                    Iterator<Integer> i = adj[n].listIterator();
                    while (i.hasNext()) {
                        stack.add(i.next());
                    }
                }
            }
        }