Approach
Breadth-first search
For Minimum Moves to Clean the Classroom, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 51 lines of Python from the credited upstream file minimum-moves-to-clean-the-classroom.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def minMoves(self, classroom, energy):7 """8 :type classroom: List[str]9 :type energy: int10 :rtype: int11 """12 DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))13 m, n = len(classroom), len(classroom[0])14 lookup = {}15 r = c = -116 for i in xrange(m):17 for j in xrange(len(classroom[i])):18 curr = classroom[i][j]19 if curr == 'S':20 r, c = i, j21 elif curr == 'L':22 lookup[(i, j)] = len(lookup)23 lookup2 = [[[-1]*(1<<len(lookup)) for _ in xrange(n)] for _ in xrange(m)]24 lookup2[r][c][0] = energy25 q = [(r, c, 0, energy)]26 result = 027 while q:28 new_q = []29 for i, j, mask, e in q:30 if lookup2[i][j][mask] != e:31 continue32 if mask == (1<<len(lookup))-1:33 return result34 for di, dj in DIRECTIONS:35 ni, nj = i+di, j+dj36 ne = e-137 if not (0 <= ni < m and 0 <= nj < n and classroom[ni][nj] != 'X' and ne >= 0):38 continue39 new_mask = mask40 if classroom[ni][nj] == 'R':41 ne = energy42 elif classroom[ni][nj] == 'L':43 new_mask |= 1<<lookup[(ni, nj)]44 if ne <= lookup2[ni][nj][new_mask]:45 continue46 lookup2[ni][nj][new_mask] = ne47 new_q.append((ni, nj, new_mask, ne))48 q = new_q49 result += 150 return -151