Prepin
Log in

Shortest Path in a Cell

Approach / Explanation

This question presents you with a grid that represents a matrix of cells, and your goal is to determine the shortest path from the top-left cell (the starting cell) to the bottom-right cell (the destination cell). The grid will consist of 1s and 0s, where 1 signifies that the cell is unblocked and passable, while 0 indicates that the cell is blocked and impassable. Your task is to locate and return the shortest path between these two cells, counting all cells in the path, including both the starting and ending cells. If a path does not exist, you should represent this appropriately, typically by returning -1. To tackle this problem, you can employ various search algorithms, such as Depth-First Search (DFS) or Breadth-First Search (BFS). However, since you need to find the shortest path, BFS is the more appropriate choice, as it explores all neighboring cells at the current depth before moving on to the next depth level.

Suggested Answer

For example, consider the following 3x3 grid: grid = [[1,1,1], [1,0,1], [1,1,1]] In this scenario, the shortest route from the top-left corner (0, 0) to the bottom-right corner (2, 2) follows the perimeter of the grid. The cells along the shortest path can be indicated by their indices as follows: [(0,0), (0,1), (0,2), (1,2), (2,2)] Therefore, for this grid, our function should output 5, which represents the total number of cells in the shortest path.

Alternative Answer

For instance, consider the following 3x3 grid: grid = [[1,0,1], [1,1,1], [1,0,1]] In this case, the shortest path passes through the center cell of the grid, which can be represented by the indices of the cells along this path: [(0,0), (1,0), (1,1), (1,2), (2,2)] Therefore, for this grid, our function should return 5, indicating the number of cells in the shortest path. If a path does not exist, it would be prudent to use conditionals generously to address these situations and provide an appropriate outcome.

Question Details

Difficulty & Category

Medium
algorithms

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.