On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:

  • "G": go straight 1 unit;
  • "L": turn 90 degrees to the left;
  • "R": turn 90 degrees to the right.

The robot performs the instructions given in order, and repeats them forever.

Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.

Example 1:

Input: instructions = "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.

Example 2:

Input: instructions = "GG" Output: false Explanation: The robot moves north indefinitely.

Example 3:

Input: instructions = "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...

Constraints:

  • 1 <= instructions.length <= 100
  • instructions[i] is 'G', 'L' or, 'R'.

这是一道类似脑筋急转弯的题目——你想到了那个点就可以解出来,想不到就无从下手。所以我不喜欢这一题。我记录它的原因是它涉及到对转向的一般性解法,除此之外我不打算多费唇舌。如果有人好奇可以去B战搜索,有人做了极好的视频。

/** * @param {string} instructions * @return {boolean} */ var isRobotBounded = function(instructions) { const location = [0, 0] let d = 0 // 注意这个二维数组 const directionM = [ [0,1], [-1,0], [0,-1], [1,0] ] function parse(command, location) { if (command === 'G') { let add = directionM[d] location[0] += add[0] location[1] += add[1] } // 以及我们是怎么让机器人转向的。 if (command === 'L') { d = (d + 1) % 4 } if (command === 'R') d = (d - 1 + 4) % 4 } instructions.split('').forEach(c => { parse(c, location) }) if ( (location [0] === 0 && location[1] === 0) || d !== 0 ) { return true } return false };