1. 程式人生 > >[Swift]LeetCode1041. 困於環中的機器人 | Robot Bounded In Circle

[Swift]LeetCode1041. 困於環中的機器人 | Robot Bounded In Circle

etc color += them solution turn UNC gree false

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 degress 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: "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: "GG"
Output: false
Explanation: 
The robot moves north indefinetely.

Example 3:

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

Note:

  1. 1 <= instructions.length <= 100
  2. instructions[i]
    is in {‘G‘, ‘L‘, ‘R‘

在無限的平面上,機器人最初位於 (0, 0) 處,面朝北方。機器人可以接受下列三條指令之一:

  • "G":直走 1 個單位
  • "L":左轉 90 度
  • "R":右轉 90 度

機器人按順序執行指令 instructions,並一直重復它們。

只有在平面中存在環使得機器人永遠無法離開時,返回 true。否則,返回 false

示例 1:

輸入:"GGLLGG"
輸出:true
解釋:
機器人從 (0,0) 移動到 (0,2),轉 180 度,然後回到 (0,0)。
重復這些指令,機器人將保持在以原點為中心,2 為半徑的環中進行移動。

示例 2:

輸入:"GG"
輸出:false
解釋:
機器人無限向北移動。

示例 3:

輸入:"GL"
輸出:true
解釋:
機器人按 (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ... 進行移動。

提示:

  1. 1 <= instructions.length <= 100
  2. instructions[i]{‘G‘, ‘L‘, ‘R‘}

Runtime: 8 ms Memory Usage: 20.6 MB
 1 class Solution {
 2     func isRobotBounded(_ instructions: String) -> Bool {
 3         var arr:[Character] = Array(instructions)
 4         var left:Int = 0
 5         var right:Int = 0
 6         for c in arr
 7         {
 8             if c == "L"
 9             {
10                 left += 1
11                 
12             }
13             if c == "R"
14             {
15                 right += 1
16             }
17         }
18         if left == 0 && right == 0
19         {
20             return false
21         }
22         if left != 0 && right == left
23         {
24             return false
25         }
26         return true
27     }
28 }

[Swift]LeetCode1041. 困於環中的機器人 | Robot Bounded In Circle