1041.困于环中的机器人
链接:1041.困于环中的机器人
难度:Medium
标签:数学、字符串、模拟
简介:机器人按顺序执行指令 instructions,并一直重复它们。只有在平面中存在环使得机器人永远无法离开时,返回 true。否则,返回 false。
题解 1 - cpp
- 编辑时间:2023-04-11
- 执行用时:4ms
- 内存消耗:6MB
- 编程语言:cpp
- 解法介绍:做四次模拟回到原点的一定是循环。
class Solution {
public:
    bool isRobotBounded(string instructions) {
        vector<vector<int>> dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
        int n = instructions.size(), dir = 0, x = 0, y = 0;
        for (int cnt = 0; cnt < 4; cnt++) {
            for (int i = 0; i < n; i++) {
                switch (instructions[i]) {
                    case 'L': dir = (dir + 4 - 1) % 4; break;
                    case 'R': dir = (dir + 1) % 4; break;
                    case 'G': x = x + dirs[dir][0], y = y + dirs[dir][1]; break;
                }
            }
        }
        return x == 0 && y == 0;
    }
};
题解 2 - python
- 编辑时间:2023-04-11
- 执行用时:32ms
- 内存消耗:14.8MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def isRobotBounded(self, instructions: str) -> bool:
        dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        x = y = dir = 0
        for _ in range(4):
            for i in instructions:
                match i:
                    case 'L':
                        dir = (dir + 4 - 1) % 4
                    case 'R':
                        dir = (dir + 1) % 4
                    case 'G':
                        x = x + dirs[dir][0]
                        y = y + dirs[dir][1]
        return x == 0 and y == 0
题解 3 - rust
- 编辑时间:2023-04-11
- 内存消耗:2.2MB
- 编程语言:rust
- 解法介绍:同上。
const dirs: [[i32; 2]; 4] = [[1, 0], [0, 1], [-1, 0], [0, -1]];
impl Solution {
    pub fn is_robot_bounded(instructions: String) -> bool {
        let instructions = instructions.chars().collect::<Vec<char>>();
        let (mut x, mut y, mut dir) = (0, 0, 0i32);
        for _ in 0..4 {
            for i in &instructions {
                match *i {
                    'L' => {
                        dir = (dir + 4 - 1) % 4;
                    }
                    'R' => {
                        dir = (dir + 1) % 4;
                    }
                    'G' => {
                        x = x + dirs[dir as usize][0];
                        y = y + dirs[dir as usize][1];
                    }
                    _ => {}
                }
            }
        }
        x == 0 && y == 0
    }
}