Approach
Depth-first search
For Robot Room Cleaner, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 60 lines of C++ from the credited upstream file 489.cpp.
- The implementation visibly relies on hash lookup.
- 1 loop block detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1/**2 * 3 * 4 * class Robot {5 * public:6 * 7 * 8 * 9 *10 * 11 * 12 * void turnLeft();13 * void turnRight();14 *15 * 16 * void clean();17 * };18 */19 20class Solution {21 public:22 void cleanRoom(Robot& robot) {23 dfs(robot, 0, 0, 0, unordered_set<pair<int, int>, PairHash>());24 }25 26 private:27 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};28 29 struct PairHash {30 size_t operator()(const pair<int, int>& p) const {31 return p.first ^ p.second;32 }33 };34 35 void dfs(Robot& robot, int i, int j, int d,36 unordered_set<pair<int, int>, PairHash>&& seen) {37 seen.insert({i, j});38 robot.clean();39 40 41 42 for (int k = 0; k < 4; ++k) {43 const int newD = (d + k) % 4;44 const int x = i + kDirs[newD][0];45 const int y = j + kDirs[newD][1];46 if (!seen.contains({x, y}) && robot.move()) {47 dfs(robot, x, y, newD, std::move(seen));48 49 robot.turnRight();50 robot.turnRight();51 robot.move();52 53 robot.turnRight();54 robot.turnRight();55 }56 robot.turnRight(); 57 }58 }59};60