Problem Link

Description


You are given an m x n grid classroom where a student volunteer is tasked with cleaning up litter scattered around the room. Each cell in the grid is one of the following:

  • 'S': Starting position of the student
  • 'L': Litter that must be collected (once collected, the cell becomes empty)
  • 'R': Reset area that restores the student's energy to full capacity, regardless of their current energy level (can be used multiple times)
  • 'X': Obstacle the student cannot pass through
  • '.': Empty space

You are also given an integer energy, representing the student's maximum energy capacity. The student starts with this energy from the starting position 'S'.

Each move to an adjacent cell (up, down, left, or right) costs 1 unit of energy. If the energy reaches 0, the student can only continue if they are on a reset area 'R', which resets the energy to its maximum capacity energy.

Return the minimum number of moves required to collect all litter items, or -1 if it's impossible.

Β 

Example 1:

Input: classroom = ["S.", "XL"], energy = 2

Output: 2

Explanation:

  • The student starts at cell (0, 0) with 2 units of energy.
  • Since cell (1, 0) contains an obstacle 'X', the student cannot move directly downward.
  • A valid sequence of moves to collect all litter is as follows:
    • Move 1: From (0, 0) β†’ (0, 1) with 1 unit of energy and 1 unit remaining.
    • Move 2: From (0, 1) β†’ (1, 1) to collect the litter 'L'.
  • The student collects all the litter using 2 moves. Thus, the output is 2.

Example 2:

Input: classroom = ["LS", "RL"], energy = 4

Output: 3

Explanation:

  • The student starts at cell (0, 1) with 4 units of energy.
  • A valid sequence of moves to collect all litter is as follows:
    • Move 1: From (0, 1) β†’ (0, 0) to collect the first litter 'L' with 1 unit of energy used and 3 units remaining.
    • Move 2: From (0, 0) β†’ (1, 0) to 'R' to reset and restore energy back to 4.
    • Move 3: From (1, 0) β†’ (1, 1) to collect the second litter 'L'.
  • The student collects all the litter using 3 moves. Thus, the output is 3.

Example 3:

Input: classroom = ["L.S", "RXL"], energy = 3

Output: -1

Explanation:

No valid path collects all 'L'.

Β 

Constraints:

  • 1 <= m == classroom.length <= 20
  • 1 <= n == classroom[i].length <= 20
  • classroom[i][j] is one of 'S', 'L', 'R', 'X', or '.'
  • 1 <= energy <= 50
  • There is exactly one 'S' in the grid.
  • There are at most 10 'L' cells in the grid.

Solution


Python3

class Solution:
    def minMoves(self, grid: List[str], startEnergy: int) -> int:
        rows, cols = len(grid), len(grid[0])
        sx = sy = -1
        litter = []
 
        for i in range(rows):
            for j in range(cols):
                if grid[i][j] == 'S':
                    sx, sy = i, j
                elif grid[i][j] == 'L':
                    litter.append((i, j))
 
        litterIndex = {(x, y) : i for i, (x, y) in enumerate(litter)}
        litterCount = len(litter)
 
        if litterCount == 0: return 0
 
        visited = [[[-inf] * (1 << litterCount) for _ in range(cols)] for _ in range(rows)]
        visited[sx][sy][0] = startEnergy
        allMask = (1 << litterCount) - 1
        queue = deque()
        queue.append((sx, sy, startEnergy, 0, 0))
        
        while queue:
            x, y, energy, mask, moves = queue.popleft()
            
            if mask == allMask: return moves
 
            if energy == 0: continue
 
            for dx, dy in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
                if 0 <= dx < rows and 0 <= dy < cols and grid[dx][dy] != 'X':
                    newMask = mask
                    newEnergy = energy - 1
                    if grid[dx][dy] == 'R':
                        newEnergy = startEnergy 
                    elif grid[dx][dy] == 'L':
                        newMask |= (1 << litterIndex[(dx, dy)])
                        
                    if newEnergy >= 0 and newEnergy > visited[dx][dy][newMask]:
                        visited[dx][dy][newMask] = newEnergy
                        queue.append((dx, dy, newEnergy, newMask, moves + 1))
                    
        return -1