leetcode10-困于环中的机器人

题目链接:

https://leetcode.cn/problems/robot-bounded-in-circle/description/?envType=study-plan-v2&envId=programming-skills

思路:

首先,题目要寻找的是成环的情况。

1.如果经历一次指令后的方向仍为北方,要使得机器人循环困住,必须让机器人回到原点

2.如果经历一次指令后的方向不是北方,那么最多重复四次又会回到面朝北方,这种情况下机器人虽然不会回到原点,但是也一直都被环困住。

代码采用了常用的二维平面的向量坐标写法

代码:

java 复制代码
class Solution {
    public boolean isRobotBounded(String instructions) {
        //记录 0 1 2 3
        //    北东南西 坐标向量写法
        int [][] res = {
            {0,1},{1,0},{0,-1},{-1,0}
        };
        int n = instructions.length();
        int x = 0,y = 0;//记录坐标
        int faceDirect = 0;//记录朝向 一开始为0 表示指向北
        for(int i = 0;i<n;i++) {
            //直走命令
            if(instructions.charAt(i)=='G') {
                x+=res[faceDirect][0];
                y+=res[faceDirect][1];
            }
            //左转命令
            else if(instructions.charAt(i)=='L') {
                faceDirect = (faceDirect+3)%4;
                
            }
            //右转命令
            else if(instructions.charAt(i)=='R') {
                faceDirect = (faceDirect+1)%4;
            }
        }
        if( (x==0 && y==0)|| faceDirect!=0)
            return true;
        return false;
    }
}
相关推荐
开心香辣派小星2 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式
Halo_tjn2 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
摆烂z3 小时前
Docker与Jib(maven插件版)实战
java
RainbowSea3 小时前
从 Spring Boot 2.x 到 3.5.x + JDK21:一次完整的生产环境迁移实战
java·spring boot·后端
笨手笨脚の3 小时前
Spring Core常见错误及解决方案
java·后端·spring
奶油松果3 小时前
Springboot自动装配 - redis和redission
java·spring boot·redis
霍夫曼4 小时前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
VX:Fegn08954 小时前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计
荔枝hu4 小时前
springboot和shiro组合引入SseEmitter的一些坑
java·spring boot·后端·sseeitter
老华带你飞4 小时前
健身房|基于springboot + vue健身房管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端