6

I am working on below interview question and I am confuse on how to use BFS search here. I am confuse on how to deal with the blockades here?

Given a MxN matrix find the shortest path to reach a given destination cell. The robot can move up, down, left or right. The matrix also comes with set of blockades in few of the cells where the robot can't pass through. Output the minimum number of moves the robot needs to make to reach the destination. Output -1 if the destination is not reachable. Assume that the blockade will never be at the starting cell.

Input Format: First line contains the values of M and N matrix. Second line contains the cell location of the robots starting position. Third line contains the cell location of the destination. Fourth line and the lines following that will contain the locations of the blockades. The example below contains only one blockade at (2,2) where the robot can't pass through. Below is the input:

3 3
1 1
3 3
2 2

Output should be 4 for above input.

Below is what I have started but confuse on how to deal with blockades here while doing BFS search:

  public static void main(String args[] ) throws Exception {
    Scanner sc = new Scanner(System.in);
    int M = sc.nextInt();
    int N = sc.nextInt();

    int startX = sc.nextInt();
    int startY = sc.nextInt();

    int destinationX = sc.nextInt();
    int destinationY = sc.nextInt();

    while (sc.hasNext()) {
        int blockedX = sc.nextInt();
        int blockedY = sc.nextInt();
    }
}
lastr2d2
  • 3,604
  • 2
  • 22
  • 37
john
  • 11,311
  • 40
  • 131
  • 251

1 Answers1

3

You can simply view the grid as a graph: each cell is connected to its four neighbors (or fewer if it's on an edge), excluding any blockades. Using your example:

  1 2 3
1 • • •
2 • x •
3 • • •

we have the graph (using (row, col) notation):

(1,1) <-> (1,2)
(2,1) <-> (3,1)
(3,1) <-> (2,3)
(2,3) <-> (3,3)
(3,3) <-> (3,2)
(3,2) <-> (3,1)
(3,1) <-> (2,1)
(2,1) <-> (1,1)

where all edge lengths are 1. Now you can apply a standard BFS from the start node until you reach the target node, keeping track of which nodes you visit. In pseudocode:

  • Mark all cell distances as infinite except for the robot starting cell, which has distance zero (you can do this using an extra 2D array, or maybe even in-place depending on how you store the grid).
  • Initialize an empty queue of cells Q
  • Add the robot starting cell to Q
  • While Q is not empty:
    • Dequeue the next cell C from Q
    • For each non-blockade neighbor N of C (easy to determine from grid):
      • If N's distance is infinity, mark N's distance to be (C's distance) + 1, and add N to Q.
      • If N is the destination cell, return N's distance.
  • At this point we know there's no path from the start cell to the destination cell.
arshajii
  • 127,459
  • 24
  • 238
  • 287