中级农民
- 积分
- 217
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-11-30
- 最后登录
- 1970-1-1
|
LC 489 robot cleaner 第三遍,AC in 28 min
idea: backtracking
tips: get your coder-friendly custom API defined before implementation
compile errors:
missing semicolon
swapped function signatures (decode/encode backwards)
missed i/j with loc.first/loc.second
no run time errors
C++ Code:
- /**
- * // 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();
- * };
- */
- /* backtracking problem, define custom APIs first */
- class Solution {
- private:
- int state;
- public:
- Solution(): state(0){}
-
- void cleanRoom(Robot& robot) {
- /* 0. MISC */
-
- /* 1. prep */
- unordered_set<string> visited;
-
- /* 2. key algo */
- CleanRoomRec(&robot, &visited, {0, 0});
-
- /* 3. answer */
- /* void, no return */
- }
-
- void CleanRoomRec(Robot* robot, unordered_set<string>* visited, pair<int, int> loc){
- /* before branching */
- if(visited->find(Encode(loc)) != visited->end())return;
- visited->emplace(Encode(loc));
- robot->clean();
-
- /* branching */
- vector<string> directions = {"N", "E", "S", "W"};
- vector<pair<int, int>> moves = {pair<int, int>(-1, 0), pair<int, int>(0, 1), pair<int, int>(1, 0), pair<int, int>(0, -1)};
- for(int i = 0; i < directions.size(); ++i){
- string dir = directions[i];
- string revDir = directions[(i+2)%4];
- if(CanEnter(dir, robot)){
- TurnTo(dir, robot);
- robot->move();
- CleanRoomRec(robot, visited, {loc.first + moves[i].first, loc.second + moves[i].second});
- TurnTo(revDir, robot);
- robot->move();
- }
- }
-
- /* done */
- }
-
- void TurnTo(string dir, Robot* robot){
- int target = 0;
- if(dir == "N")target = 0;
- if(dir == "E")target = 1;
- if(dir == "S")target = 2;
- if(dir == "W")target = 3;
- while(state != target){
- robot->turnRight();
- state += 1;
- state %= 4;
- }
- }
-
- void TurnAround(Robot* robot){
- robot->turnRight();
- robot->turnRight();
- state += 2;
- state %= 4;
- }
-
- bool CanEnter(string dir, Robot* robot){
- TurnTo(dir, robot);
- bool ans = robot->move();
- if(ans){
- TurnAround(robot);
- robot->move();
- }
- return ans;
- }
-
- string Encode(const pair<int, int>& loc){
- return to_string(loc.first) + " " + to_string(loc.second);
- }
-
- pair<int, int> Decode(const string& loc){
- int div = loc.find(" ");
- string strI = loc.substr(0, div);
- string strJ = loc.substr(div + 1);
- return {stoi(strI), stoi(strJ)};
- }
- };
复制代码 |
|