BFS

Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree (See method 2 of this post). The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex. For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth First Traversal of the following graph is 2, 0, 3, 1.

Following are the implementations of simple Breadth First Traversal from a given source.

The implementation uses adjacency list representation of graphs. STL‘s list container is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal.

// Adjacency List
public class Solution {

    public static void BFS(ArrayList<Integer> edges[], int sv, boolean visited[]) {
        Queue<Integer> q = new LinkedList<>();
        q.add(sv);
        int n = edges.length;
        visited[sv] = true;
        while (q.size() != 0) {
            int front = q.poll();
            System.out.print(front + " ");
            for (int x : edges[sv])
                if (!visited[x]) {
                    q.add(x);
                    visited[x] = true;
                }
        }
    }

    public static void print(ArrayList<Integer> edges[]) {
        boolean[] visited = new boolean[edges.length];
        for (int i = 0; i < edges.length; i++)
            if (!visited[i])
                BFS(edges, i, visited);
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int V = s.nextInt();
        int E = s.nextInt();
        ArrayList<Integer> edges[] = new ArrayList[V];
        for (int i = 0; i < V; i++)
            edges[i] = new ArrayList<>();
        for (int i = 0; i < E; i++) {
            int fv = s.nextInt();
            int sv = s.nextInt();
            edges[fv].add(sv);
            edges[sv].add(fv);
        }
        print(edges);
    }
}

// Adjacency matrix
public class Solution {

    public static void BFS(int edges[][], int sv, boolean visited[]) {
        Queue<Integer> q = new LinkedList<>();
        q.add(sv);
        int n = edges.length;
        visited[sv] = true;
        while (q.size() != 0) {
            int front = q.poll();
            System.out.print(front + " ");
            for (int i = 0; i < n; i++)
                if (edges[front][i] == 1 && !visited[i]) {
                    q.add(i);
                    visited[i] = true;
                }
        }
    }

    public static void print(int edges[][]) {
        boolean[] visited = new boolean[edges.length];
        for (int i = 0; i < edges.length; i++)
            if (!visited[i])
                BFS(edges, i, visited);
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int V = s.nextInt();
        int E = s.nextInt();
        int edges[][] = new int[V][V];
        for (int i = 0; i < E; i++) {
            int fv = s.nextInt();
            int sv = s.nextInt();
            edges[sv][fv] = 1;
            edges[fv][sv] = 1;
        }
        print(edges);
    }
}

Last updated