4

What is the order of DFS or BFS traversals for graphs when there may be vertices which have outdegrees of 0 if we want to do DFS/BFS from a given vertex {0..n-1}.

enter image description here

Below is one BFS implementation for a graph

import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Queue;

public class BreadthFirstSearch {

    static class Graph {
        int V;
        LinkedList[] vertexList;

        Graph(int v) {
            this.V = v;
            vertexList = new LinkedList[v];

            for (int i = 0; i < v; i++) {
                vertexList[i] = new LinkedList<>();
            }
        }
    }

    private void addEdge(Graph graph, int src, int dest) {
        graph.vertexList[src].add(dest); // Directed Graph Only
    }

    private void bfs(Graph graph, int vertex) {

        if (vertex > graph.V) {
            throw new IllegalArgumentException("Value not defined");
        }
        boolean visited[] = new boolean[graph.V];

        Queue<Integer> queue = new LinkedList<>();

        queue.add(vertex);
        while (!queue.isEmpty()) {
            int a = queue.poll();
            if (!visited[a]) {
                System.out.print(a + " ");
                visited[a] = true;

            }
            for (Object o : graph.vertexList[a]) {
                int n = (int) o;
                if (!visited[n]) {
                    queue.add(n);
                }
            }
        }
    }

    private void traverseGraphList(Graph G) {
        int i = 0;
        for (LinkedList list : G.vertexList) {
            ListIterator itr = list.listIterator();
            System.out.print("src: " + i++ + " ");
            while (itr.hasNext()) {
                System.out.print(" -> " + itr.next());
            }
            System.out.println();
        }
    }

    public static void main(String args[]) {
        BreadthFirstSearch g = new BreadthFirstSearch();
        int n = 8;
        Graph graph = new Graph(n);
        g.addEdge(graph, 0, 1);
        g.addEdge(graph, 0, 2);
        g.addEdge(graph, 1, 2);
        g.addEdge(graph, 2, 0);
        g.addEdge(graph, 2, 3);
        g.addEdge(graph, 3, 3);
        g.addEdge(graph, 3, 4);
        g.addEdge(graph, 5, 4);
        g.addEdge(graph, 5, 6);
        g.addEdge(graph, 7, 6);
        System.out.println("BFS starting from node 2");
        g.bfs(graph, 2);

        System.out.println();
        g.traverseGraphList(graph);
        //2 0 3 1 4

    }
}

The output is 2 0 3 1 4

entpnerd
  • 10,049
  • 8
  • 47
  • 68
Mr X
  • 1,637
  • 3
  • 29
  • 55
  • `What is the order in which the DFS or BFS traversal is done in graph` AFAIK the order is dependent upon how they are placed in the queue, and how they are placed in the queue is dependent upon either the data structure representing the graph, the algorithm that walks the graph or both. There is no one conical order in general. There may be specific implementations that define an order, but I don't know of that being a requirement to be either DFS or BFS. – Guy Coder Jan 07 '20 at 15:17
  • So in my case if I using stack/queue the traversal stops after hitting 4 or just say we pass 4 initially and it don't find any adjacent nodes, then at random can we pick any node which is not visited till yet and continue the traversal and update the node till we hit the another block ? – Mr X Jan 07 '20 at 15:31
  • `then at random can we pick any node which is not visited till yet and continue the traversal and update the node till we hit the another block ?` No, that wold not be DFS or BFS. What you seek seems closer to checking if a graph is connected or if a spanning tree can be created. – Guy Coder Jan 07 '20 at 15:41
  • 1
    Or you might be seeking the minimum set of nodes that via [reachability](https://en.wikipedia.org/wiki/Reachability) can cover the graph. – Guy Coder Jan 07 '20 at 15:47
  • You need to explain what you hope to accomplish by traversing this graph – Matt Timmermans Jan 07 '20 at 17:32
  • _"the traversal stops after hitting 4"_ that is correct for this case. _" then at random can we pick any node"_ yes, you can do it - it is like starting a new search, say `g.bfs(graph, 6)` – c0der Jan 12 '20 at 06:09

2 Answers2

1

If you want to traverse all the nodes of the graph, then you should be aware that since there are nodes that are not reachable from your selected root node, you won't be able to traverse them while using a single BFS/DFS.

The order on which the nodes are traversed is dependent on the implementation of your BFS/DFS. In your case, it depends on the order you insert each node to the adjacency list.

If you would like to traverse the whole graph, then you should maintain which nodes are visited and then run BFS/DFS for each non-visited node (e.g by using a loop). Particularly, the order of appearance of the traversed nodes again depend on the ordering of the items on which you will actually loop.

davuinci
  • 60
  • 10
1

So from what I can see, the implementation of BFS is fine. IMO, its output is what I would expect for a standard implementation of the algorithm when the input to the initial call has 2 set for the vertex parameter.

That being said, not all directed graphs are completely traversable from any given node. Based on the directions of the arrows, when I start traversing at node 2, I can really only get to nodes 0, 1, 3, and 4. Nodes 5, 6, and 7 aren't reachable from node 2 because 5 points to 4, but 4 doesn't point to 5.

If you want to truly traverse the entire graph you will need to amend your BFS algorithm such that if at the end of the current implementation, the length of the visited array is less than the length of the vertexList array, then you will need to find the next element in vertexList that isn't present in visited until the lengths of the two arrays match.

entpnerd
  • 10,049
  • 8
  • 47
  • 68