# BFS

[Breadth First Traversal (or Search)](http://en.wikipedia.org/wiki/Breadth-first_search) for a graph is similar to Breadth First Traversal of a tree (See method 2 of [this post](https://www.geeksforgeeks.org/level-order-tree-traversal/)). 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.

[![](https://media.geeksforgeeks.org/wp-content/uploads/bfs-5.png)](https://media.geeksforgeeks.org/wp-content/uploads/bfs-5.png)

### [Recommended: Please solve it on “**PRACTICE** ” first, before moving on to the solution.](https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/1) 

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

The implementation uses [adjacency list representation](http://en.wikipedia.org/wiki/Adjacency_list) of graphs. [STL](http://en.wikipedia.org/wiki/Standard_Template_Library)‘s [list container](http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html#LIST) is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal.

```java
// 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);
    }
}
```

