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
- 50 lines of Java from the credited upstream file 489.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 * interface Robot {5 * 6 * 7 * public boolean move();8 *9 * 10 * 11 * public void turnLeft();12 * public void turnRight();13 *14 * 15 * public void clean();16 * }17 */18 19class Solution {20 public void cleanRoom(Robot robot) {21 dfs(robot, 0, 0, 0, new HashSet<>());22 }23 24 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};25 26 private void dfs(Robot robot, int d, int i, int j, Set<Pair<Integer, Integer>> seen) {27 seen.add(new Pair<>(i, j));28 robot.clean();29 30 31 32 for (int k = 0; k < 4; ++k) {33 final int newD = (d + k) % 4;34 final int x = i + DIRS[newD][0];35 final int y = j + DIRS[newD][1];36 if (!seen.contains(new Pair<>(x, y)) && robot.move()) {37 dfs(robot, newD, x, y, seen);38 39 robot.turnRight();40 robot.turnRight();41 robot.move();42 43 robot.turnRight();44 robot.turnRight();45 }46 robot.turnRight(); 47 }48 }49}50