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
- 60 lines of C++ from the credited upstream file minimum-moves-to-clean-the-classroom.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 5 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 {6public:7 int minMoves(vector<string>& classroom, int energy) {8 static const vector<pair<int, int>> DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};9 10 const int m = size(classroom), n = size(classroom[0]);11 unordered_map<int, int> lookup;12 int r = -1, c = -1;13 for (int i = 0; i < m; ++i) {14 for (int j = 0; j < n; ++j) {15 if (classroom[i][j] == 'S') {16 r = i;17 c = j;18 } else if (classroom[i][j] == 'L') {19 lookup[i * n + j] = size(lookup);20 }21 }22 }23 24 vector<vector<vector<int>>> lookup2(m, vector<vector<int>>(n, vector<int>(1 << size(lookup), -1)));25 lookup2[r][c][0] = energy;26 vector<tuple<int, int, int, int>> q = {{r, c, 0, energy}};27 for (int result = 0; !empty(q); ++result) {28 vector<tuple<int, int, int, int>> new_q;29 for (const auto& [i, j, mask, e] : q) {30 if (lookup2[i][j][mask] != e) {31 continue;32 }33 if (mask == (1 << size(lookup)) - 1) {34 return result;35 }36 for (const auto& [di, dj] : DIRECTIONS) {37 const int ni = i + di, nj = j + dj;38 int ne = e - 1;39 if (!(0 <= ni && ni < m && 0 <= nj && nj < n && classroom[ni][nj] != 'X' && ne >= 0)) {40 continue;41 }42 int new_mask = mask;43 if (classroom[ni][nj] == 'R') {44 ne = energy;45 } else if (classroom[ni][nj] == 'L') {46 new_mask |= 1 << lookup[ni * n + nj];47 }48 if (ne <= lookup2[ni][nj][new_mask]) {49 continue;50 }51 lookup2[ni][nj][new_mask] = ne;52 new_q.emplace_back(ni, nj, new_mask, ne);53 }54 }55 q = move(new_q);56 }57 return -1;58 }59};60