Breadth First Traversal (BFS) on a 2D array using JAVA.


Introduction

Breadth-First Traversal (BFS) is a graph traversal technique that begins at a source cell and moves outward, layer by layer, to reach all nodes in a 2D array. It visits nodes in order of their distance from the source, beginning with the closest ones and working its way outward. In unweighted graphs, BFS guarantees that there is a shortest path to every reachable cell.

To successfully apply BFS to a 2D array, it is necessary to have a firm grasp of what is a 2D array. In computer science, a grid, map, or maze can be represented as a 2D array, a matrix like data structure having rows and columns. Knowing how data is indexed and retrieved across rows and columns is crucial for effective implementation

Step-by-step explanation of BFS on a 2D array

Breadth First Traversal (BFS) is an algorithm used to visit and explore all the nodes in a graph, including 2D arrays, in a breadth ward motion. In the context of a 2D array, BFS begins its traversal from a given starting cell and explores its neighboring cells before moving on to their neighbors in a level-by-level manner. The step-by-step explanation of BFS on a 2D array is as follows −

  • Initialize a queue data structure and an auxiliary data structure (e.g., a visited array) to keep track of visited cells.

  • Enqueue the starting cell into the queue and mark it as visited in the auxiliary data structure.

  • Start a loop that continues until the queue becomes empty

  • Within the loop, dequeue a cell from the front of the queue. This cell represents the current node being visited.

  • Explore all the neighboring cells (up, down, left, right) of the current cell.

  • For each un-visited neighboring cell, enqueue it into the queue and mark it as visited in the auxiliary data structure.

  • Repeat steps 4 to 6 until the queue becomes empty, indicating that all cells connected to the starting cell have been visited.

Java Execution

import java.util.LinkedList;
import java.util.Queue;
public class BFSTraversalOn2DArray {
   static class Cell {
      int row;
      int col;
   Cell(int row, int col) {
      this.row = row;
      this.col = col;
      }
   }
   public static void BFS_2D_Array(int[][] grid, int start_i, int start_j) {
      int rows = grid.length;
      int cols = grid[0].length;
      boolean[][] visited = new boolean[rows][cols];
      
   // Define the directions for exploring neighbors (up, down, left, right)
   int[] dr = {0, 0, 1, -1};
   int[] dc = {1, -1, 0, 0};
   
   Queue<Cell> queue = new LinkedList<>();
   
   queue.add(new Cell(start_i, start_j));
   visited[start_i][start_j] = true;
   
   while (!queue.isEmpty()) {
      Cell currentCell = queue.poll();
      int i = currentCell.row;
      int j = currentCell.col;
      System.out.println("Visiting cell at (" + i + ", " + j + ")"); // Print the visited cell
      
      for (int k = 0; k < 4; k++) { // Four directions: up, down, left, right
         int ni = i + dr[k];
         int nj = j + dc[k];
         
      // Check if the new cell (ni, nj) is within the grid boundaries
         if (ni >= 0 && ni < rows && nj >= 0 && nj < cols && !visited[ni][nj]) { 
            queue.add(new Cell(ni, nj));
            visited[ni][nj] = true;
            }
         }
      }
   }
   public static void main(String[] args) {
      int[][] grid = {
         {1, 0, 1, 0},
         {0, 1, 0, 1},
         {1, 0, 1, 0}
   };
      int start_i = 1;
      int start_j = 2;
      
      System.out.println("Starting BFS traversal from cell (1, 2) in the 2D array.");
      BFS_2D_Array(grid, start_i, start_j);
   }
}

Output

Starting BFS traversal from cell (1, 2) in the 2D array.
Visiting cell at (1, 2)
Visiting cell at (1, 3)
Visiting cell at (1, 1)
Visiting cell at (2, 2)
Visiting cell at (0, 2)
Visiting cell at (2, 3)
Visiting cell at (0, 3)
Visiting cell at (1, 0)
Visiting cell at (2, 1)
Visiting cell at (0, 1)
Visiting cell at (2, 0)
Visiting cell at (0, 0)

Tree Representation of the matrix

Traversing 2D Arrays

  • Different traversal techniques: row-major vs. column-major

  • When traversing a 2D array using BFS, you can opt for either row-major or column major traversal. Row-major involves iterating through rows before columns, while column-major traverses columns before rows, impacting BFS performance based on memory layout

  • Handling edge cases and boundary conditions

  • Properly managing edge cases and boundaries is vital during BFS on a 2D array. Addressing cells on the array's edges, which lack all four neighbors, is crucial to avoid errors. Handling out-of-bounds cells as obstacles or ignoring them is necessary

  • Avoiding revisiting cells and cycles in a graph

  • Preventing revisits to already processed cells and handling cycles in the graph representation of the 2D array is essential. Use a data structure like a hash set to mark visited cells and skip already visited neighbors during BFS.

Finding Shortest Paths

Adapting BFS to find shortest paths on a 2D array

Adapting BFS to find shortest paths on a 2D array BFS can determine the shortest path between two points in a 2D array. Commencing from the source and ending at the destination cell, BFS maintains parent information for path reconstruction.

Tracking parent nodes for path reconstruction

During BFS, tracking parent nodes for each cell allows reconstructing the shortest path from the destination back to the source.

Handling obstacles and weighted edges in the context of shortest paths

When obstacles or weighted edges exist in the 2D array, BFS should mark obstacles as visited and modify the queue for weighted edges, prioritizing lower weights for more efficient shortest path calculations

In 2D arrays, comparing BFS with DFS

The two most basic techniques for traversing graphs and 2D arrays are breadth-first traversal (BFS) and depth-first traversal (DFS). BFS creates a level-by-level exploration by first visiting nodes on the same level. In contrast, depth-first searching (DFS) travels as far as feasible along each branch before reversing course.

Whether you use BFS or DFS to solve a problem is conditional on its details. When finding the shortest path or the fewest number of steps is critical, BFS should be used since it ensures that the first solution identified is the best one. However, DFS is recommended when memory use is limited or when numerous solutions exist for a given path, as it may search fewer nodes in these cases. Choosing between BFS and DFS for 2D array traversals is ultimately determined by the nature of the problem and the desired qualities of the solution.

Real-life Applications of BFS Algorithm

  • BFS on a 2D map for robot navigation −

    • Utilizing BFS to guide robots through complex environments represented as 2D maps.

    • The algorithm explores adjacent cells layer by layer, efficiently finding the shortest path

    • Enables robots to avoid obstacles, optimize movement, and reach theirdestination effectively.

    • Widely used in autonomous vehicles, warehouse logistics, and robotic exploration missions

  • BFS-based algorithms in path finding applications −

    • Employing BFS as a fundamental building block for path finding in various applications.

    • Used in video games to find optimal routes for characters or NPCs

    • In route planning for GPS and mapping services to compute the shortest path between locations

    • Applied in network routing protocols to ensure efficient data packet

Conclusion

Breadth First Traversal (BFS) on a 2D array is a fundamental algorithm for solving graph based problems and mazes. Java's implementation of BFS efficiently examines the grid using a queue data structure, providing a concise and straightforward method for locating connected components, shortest paths, and solving various puzzles. BFS is a potent instrument for navigating and analyzing 2D arrays, contributing to the success of numerous real-world applications, thanks to its adaptability and the robust language features of Java

Someswar Pal
Someswar Pal

Studying Mtech/ AI- ML

Updated on: 28-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements