0

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;
                    }
                }
            }
    }
2
  • In DFS, we need to visit all children of a node. This, in essence, means we need two loops: one for the termination condition, one to iterate over all children of the current node. Normally, we do this by adding a Dequeue<...> of work to do. If we read and write from the same side, we have a DFS algorithm. If we read form one side, but write to anoteher, we have BFS. I have a DFS implementation here if you want to take a look. Commented Jan 4, 2023 at 16:42
  • Also, if the target node is a final node of the graph or even absent at all, then all nodes will be traversed. Commented Jan 4, 2023 at 17:04

1 Answer 1

2

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());
                }
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.