• leetcode 1041. 困于环中的机器人


    题目地址 : https://leetcode-cn.com/problems/robot-bounded-in-circle/

    在无限的平面上,机器人最初位于 (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'} 中

    解答

    满足不循环的情况只有一种 坐标有变化 最后方向与最开始方向相反,其余都是循环情况

     1 class Solution {
     2 public:
     3     const int up = 0;
     4 const int right = 1;
     5 const int down = 2;
     6 const int myleft = 3;
     7 
     8 bool isRobotBounded(string instructions) {
     9     int x = 0; int y = 0; int direct = up;
    10     int count = 0;
    11     for (int i = 0; i < instructions.size(); i++) {
    12         if (instructions[i] == 'G') {
    13             if (direct == up) {
    14                 y += 1; count++;
    15             }
    16             else if (direct == down) {
    17                 y -= 1; count++;
    18             }
    19             else if (direct == myleft) {
    20                 x -= 1; count++;
    21             }
    22             else {
    23                 x += 1; count++;
    24             }
    25 
    26         }
    27         else if (instructions[i] == 'L') {
    28             direct = (direct + 4 - 1) % 4;
    29 
    30         }
    31         else if (instructions[i] == 'R') {
    32             direct = (direct + 1) % 4;
    33         }
    34     }
    35     if (x == 0 && y == 0)
    36         return true;
    37     if (direct != up)
    38         return true;
    39 
    40 
    41     return false;
    42 }
    43 };
    View Code

    执行用时 : 4 ms, 在Robot Bounded In Circle的C++提交中击败了96.40% 的用户 内存消耗 : 8.4 MB, 在Robot Bounded In Circle的C++提交中击败了100.00% 的用户

    作者:defddr
    链接:https://leetcode-cn.com/problems/two-sum/solution/mo-ni-yu-fa-ti-mu-by-defddr/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    基于概率论的分类方法:朴素贝叶斯
    【目录】机器学习 笔记
    决策树原理及分类实战
    k-近邻算法实现“电影、约会网站、手写数字识别”分类
    多线程互斥锁、读写锁
    21.快速排序实现(快排)
    系统架构资料收集
    20.排序之冒泡、直插、希尔排序方法
    19.散列表(哈希表)查找
    18.平衡二叉树(AVL树)、多路树查找(B树)概念
  • 原文地址:https://www.cnblogs.com/itdef/p/11026433.html
Copyright © 2020-2023  润新知