Mark As Completed Discussion

Now let's get back to our main algorithm. To make the BFS work for a grid, we first define an array of all the possible directions that we can move in (up, down, diagonals), as unlike graphs grids are navigated by incrementing the x and y positions. We must also modify how we store elements in our plain old queue. Along with the value at each cell, the positions of cells are also stored. In this way, by incrementing the x and y values, we can move in the eight possible directions. As we traverse through these eight directions, we check for a couple of things,

  • The value at the next cell (it should be 0, we do not want to go to cells with a value of 1)
  • The x and y values of the next cell (they should not be out of bounds of the grid)

If the above conditions are met, the position and values of the next cell are successfully added to the queue. However, we would like to ensure that the current cell is not traversed again and that it does not show up while we check the eight possible directions for any other cell. To prevent such a case from occurring, the value at the current cell is changed from 0 to 1 to indicate that this position has already been visited. This process is repeated until we reach the bottom-right cell of the matrix.

Main Algorithm