 # Breadth-First Search (BFS) in 2D Matrix/2D-Array

Objective: Given a two-dimensional array or matrix, Do the breadth-First Search (BFS) to print the elements of the given matrix. Implement a Breadth-first traversal in an iterative manner.

Example:

```int [][] grid = new int[][] {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}}
Output:
1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16
```

Approach – Use Queue

As we know queue is used for BFS.

• Initialize queue.
• Initialize 2d boolean array, the same size as the original array. This will help us in avoiding traversal to go in loops.
• Add the first element position (element at (0,0), row=0, column=0) to queue
• Now until the queue is not empty
• Take out the position from the queue. Split it by “,” to get the row index and column index. and check if indexes are within the range of given matrix and marked false in the visited[] array, if not then ignore it and get the next position from the queue. If indexes are valid and not visited, then print the element.
• Mark the element in the visited array.
• Add the element positions from left, right, down and up from the current element into the queue.
• See the code below for more understanding.

Complete Code:

Output:

```Breadth-First Traversal:
1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16
```