[Math] leetcode 1041 Robot Bounded In Circle

problem: https://leetcode.com/problems/robot-bounded-in-circle/

        As the hint mentions, we can keep track of the robot's position, when it finally return to the original position, or its direction is changed( no longer facing north), we can return true.

class Solution {
public:
    vectorint,int>> dir {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    bool isRobotBounded(string instructions) {
        pair<int,int> pos { 0, 0 };
        int n = instructions.size();
        int cur = 0;
      //  cout << "n = " << n << endl;
        for(int i = 0; i < n ;i++)
        {
            char ch = instructions[i];
         //   cout << ch << " " << cur << endl;
            if(ch == 'G')
            {
                pos.first += dir[cur].first;
                pos.second += dir[cur].second;
            }
            else if(ch == 'L')
            {
                cur = (cur + 1) % 4;
            }
            else if(ch == 'R')
            {
                cur = (cur - 1 + 4) % 4;
            }
        }
        if(pos == make_pair(0,0)) return true;
        if(cur != 0) return true;
        return false;
    }
};

 

转载于:https://www.cnblogs.com/fish1996/p/11373676.html

你可能感兴趣的:([Math] leetcode 1041 Robot Bounded In Circle)