zoukankan      html  css  js  c++  java
  • leetcode1041困于环中的机器人

    题目如下,一道简单的模拟

    在无限的平面上,机器人最初位于 (0, 0) 处,面朝北方。机器人可以接受下列三条指令之一:
    
    "G":直走 1 个单位
    "L":左转 90"R":右转 90 度
    机器人按顺序执行指令 instructions,并一直重复它们。
    
    只有在平面中存在环使得机器人永远无法离开时,返回 true。否则,返回 false

    题解

    可以通过观察发现,机器人最多进行4次输入的字符串对应的操作就可以到达远点,我选择循环四次,直接看结果是不是原点。代码如下

    class Solution {
        public boolean isRobotBounded(String instructions) {
            int x=0;
            int y = 0;
            int t = 4;
            int state = 1;
            while (t>0) {
                for (int i = 0; i < instructions.length(); i++) {
                    if (instructions.charAt(i) == 'L') {
                        state--;
                    }
    
                    if (instructions.charAt(i) == 'R') {
                        state++;
                    }
                    if (state == 0) state = 4;
                    if (state == 5) state = 1;
                    if (instructions.charAt(i) == 'G') {
                        switch (state) {
                            case 1:
                                y++;break;
                            case 2:
                                x++;break;
                            case 3:
                                y--;break;
                            case 4:
                                x--;break;
                        }
                    }
                }
                t--;
            }
            if(x==0&&y==0){
                return true;
            }else {return false;}
        }
    }
    
  • 相关阅读:
    路由器的配置及使用
    OSI与TCP/IP网络模型
    IP地址
    C++中的虚函数
    虚基类
    【idea】jrebel
    JSON(来自ww3school)
    get与post
    Ajax(来自w3school)
    EasyUI——combotree
  • 原文地址:https://www.cnblogs.com/yfc0818/p/11072590.html
Copyright © 2011-2022 走看看