/** * // This is the robot's control interface. * // You should not implement it, or speculate about its implementation * class Robot { * public: * // Returns true if the cell in front is open and robot moves into the cell. * // Returns false if the cell in front is blocked and robot stays in the current cell. * bool move(); * * // Robot will stay in the same cell after calling turnLeft/turnRight. * // Each turn will be 90 degrees. * void turnLeft(); * void turnRight(); * * // Clean the current cell. * void clean(); * }; */classSolution {public: vector<vector<int>> dirs{{-1,0}, {0,1}, {1,0}, {0,-1}};voiddfs(Robot&robot,int x,int y,int dir,unordered_map<int,unordered_set<int>> &visited) {visited[x].insert(y); robot.clean();for (int i =0; i <4; ++i) {int cur = (i + dir) %4, nx = x +dirs[cur][0], ny = y +dirs[cur][1];if (visited.count(nx) &&visited[nx].count(ny) ||!robot.move()) {robot.turnRight();continue; }dfs(robot, nx, ny, cur, visited); // 回溯到上个位置,同方向 // 走回到当前位置robot.turnRight();robot.turnRight();robot.move();robot.turnLeft();robot.turnLeft(); // 转到下一个DFS方向robot.turnRight(); } }voidcleanRoom(Robot& robot) { unordered_map<int, unordered_set<int>> visited;dfs(robot,0,0,0, visited); }};