joshita / dev

Published

- 2 min read

Shortest path in binary matrix

img of Shortest path in binary matrix

Shortest path in a binary matrix

The question is trying to ask you few things

  1. If this is shortest path question then we need to have BFS implemeneted

  2. This is a 2d array hence we need to have move the pointer to get a 2d array

  3. Important part of this question is to move in directions such that many repeated computations dont happen or we skip them For that the trick is to keep the direction array in mind, think that for a 3*3 matrix you are sitting at the middle of the matrix [ (-1,-1) (-1,0) (-1, 1) (0, -1) (0, 0) (0, 1) (1, -1) (1, 0) (1, 1)
    ]

        private void bfs (int [][] grid, int row, int col) {
         int [][] direction = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; //8 directions to reach a matrix
         //including diagonals
         //each cell as it gets visited gets updated with the distance and when you reach end thats the shortest path to reach n-1, m-1 cell
         Queue<int[]> queue = new LinkedList<>();
         queue.add(new int[]{0,0});
         while (!queue.isEmpty()) {
             int[] cell = queue.peek();
             List<int[]> neighbours = getNeighbours(direction, grid, cell[0], cell[1], grid[cell[0]][cell[1]]);
             for(int[] neighbour : neighbours) {
                 queue.add(new int[]{neighbour[0], neighbour[1]});
             }
         }
     }
     private List<int[]> getNeighbours(int [][] directions, int [][] grid, int row, int col, int distance) {
         List<int[]> list = new ArrayList<>();
         for (int[] direction : directions) {
             int newRow = row + direction[0];
             int newCol = col + direction[1];
    
             if(newRow < 0 || newCol > grid.length -1 || grid[newRow][newCol] != 1) {
                 continue;
             }
             list.add(new int[]{newRow, newCol});
             grid [newRow][newCol] = distance +1;
         }
         return list;
     }