LeetCode 1041. 困于环中的机器人
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 1041. 困于环中的机器人
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
在無限的平面上,機器人最初位于 (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 <= instructions.length <= 100 instructions[i] 在 {'G', 'L', 'R'} 中來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/robot-bounded-in-circle
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
4次循環指令后,能回到原點,就永遠走不出去
class Solution { public:bool isRobotBounded(string instructions) {vector<vector<int>> dir = {{0,1},{1,0},{0,-1},{-1,0}};int x = 0, y = 0, d = 0, n = 4;while(n--)for(char ch : instructions) {if(ch == 'G'){x += dir[d][0];y += dir[d][1];}else if(ch == 'L')d = (d-1+4)%4;elsed = (d+1)%4;}return x==0 && y==0;} };4 ms 6.2 MB
或者是,一次指令后,在原點,或者方向變了,就一定能再走回來。
class Solution { public:bool isRobotBounded(string instructions) {vector<vector<int>> dir = {{0,1},{1,0},{0,-1},{-1,0}};int x = 0, y = 0, d = 0, n = 4;for(char ch : instructions) {if(ch == 'G'){x += dir[d][0];y += dir[d][1];}else if(ch == 'L')d = (d-1+4)%4;elsed = (d+1)%4;}return (x==0 && y==0) || d!=0;} };4 ms 6.5 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 1041. 困于环中的机器人的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天池 在线编程 求和查找
- 下一篇: LeetCode 1229. 安排会议日