Problem Description
Given an m x n grid representing a warehouse, the grid contains walls ('#'), floors ('.'), one box ('B'), one target ('T'), and one player ('S'). The goal is to determine the minimum number of pushes needed to move the box to the target cell. The player can move freely on floors but cannot pass through walls or the box. A push is only valid if the player can reach the required position behind the box (opposite the push direction) without moving the box. Return -1 if the target cannot be reached.
Key Insights
- The problem involves two layers of search: one to push the box and another to validate the player’s path.
- States are defined by both the box’s and the player's positions.
- A BFS is used to guarantee that the first time the box reaches the target, it is done with the minimum number of pushes.
- Before every push, perform a secondary BFS to check if the player can reach the required position to push the box.
- Maintain a visited set to avoid re-exploring the same (box, player) state.
Space and Time Complexity
Time Complexity: O(M * N * M * N) in the worst-case scenario due to exploring states in an m x n grid. Space Complexity: O(M * N * M * N) for storing visited states.
Solution
We solve the problem using a double BFS approach. The outer BFS explores states defined by the box and player positions along with the count of pushes. For each potential push direction, we check if the destination for the box is valid and if the player can reach the necessary spot behind the box using a helper BFS. This layered check ensures that every push is valid per game rules. We use a queue to manage the BFS and a set to remember visited states.