Problem Description
Given a grid where each cell can be an obstacle ('X'), free space ('O'), your starting point ('*'), or food ('#'), find the shortest path (in steps) from your starting point to any food cell. You can only move in the four cardinal directions (north, east, south, west). Return the number of steps in the shortest path, or -1 if no such path exists.
Key Insights
- Use Breadth-First Search (BFS) to explore the grid level by level.
- The BFS guarantees that when a food cell ('#') is reached, the current distance is the shortest.
- Maintain a visited structure to avoid re-processing the same cell.
- Consider boundary and obstacle ('X') conditions while traversing.
Space and Time Complexity
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns since each cell is processed at most once. Space Complexity: O(m * n) in the worst case due to the queue and visited matrix.
Solution
We use Breadth-First Search (BFS) starting from the cell marked with '*'. The BFS uses a queue to explore neighbors in the four allowed directions (up, down, left, right). Each level of BFS represents one step in the path. As soon as a cell containing food ('#') is reached, the current step count is returned. We also maintain a visited matrix to ensure that cells are not revisited, which could otherwise result in cycles or redundant processing. This approach ensures that the first time we encounter food, we have found the shortest possible path.