Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/2069.html

2069. Walking Robot Simulation II (Medium)

A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions ("North", "East", "South", and "West"). A robot is initially at cell (0, 0) facing direction "East".

The robot can be instructed to move for a specific number of steps. For each step, it does the following.

  1. Attempts to move forward one cell in the direction it is facing.
  2. If the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step.

After the robot finishes moving the number of steps required, it stops and awaits the next instruction.

Implement the Robot class:

  • Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing "East".
  • void move(int num) Instructs the robot to move forward num steps.
  • int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y].
  • String getDir() Returns the current direction of the robot, "North", "East", "South", or "West".

 

Example 1:

example-1

Input
["Robot", "move", "move", "getPos", "getDir", "move", "move", "move", "getPos", "getDir"]
[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]
Output
[null, null, null, [4, 0], "East", null, null, null, [1, 2], "West"]

Explanation
Robot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.
robot.move(2);  // It moves two steps East to (2, 0), and faces East.
robot.move(2);  // It moves two steps East to (4, 0), and faces East.
robot.getPos(); // return [4, 0]
robot.getDir(); // return "East"
robot.move(2);  // It moves one step East to (5, 0), and faces East.
                // Moving the next step East would be out of bounds, so it turns and faces North.
                // Then, it moves one step North to (5, 1), and faces North.
robot.move(1);  // It moves one step North to (5, 2), and faces North (not West).
robot.move(4);  // Moving the next step North would be out of bounds, so it turns and faces West.
                // Then, it moves four steps West to (1, 2), and faces West.
robot.getPos(); // return [1, 2]
robot.getDir(); // return "West"

 

Constraints:

  • 2 <= width, height <= 100
  • 1 <= num <= 105
  • At most 104 calls in total will be made to move, getPos, and getDir.

Similar Questions:

Solution 1.

  • // OJ: https://leetcode.com/problems/walking-robot-simulation-ii/
    // Time: 
    //      move: O(W + H)
    //      Robot, getPos, getDir: O(1)
    // Space: O(1)
    class Robot {
        int dir = 0, dirs[4][2] = { {1,0},{0,1},{-1,0},{0,-1} }, w, h, perimeter, x = 0, y = 0;
        string text[4] = {"East","North","West","South"};
    public:
        Robot(int width, int height) : w(width), h(height), perimeter(2*(w + h - 2)) {}
        void move(int k) {
            if (k >= perimeter) {
                k %= perimeter;
                if (x == 0 && y == 0 && dir == 0) dir = 3; // Special case: if we are at the beginning (x = 0, y = 0 and facing east), after the round trip, the direction becomes south.
            }
            while (k > 0) {
                auto &[dx, dy] = dirs[dir];
                int nx = x + dx, ny = y + dy;
                if (nx < 0 || ny < 0 || nx >= w || ny >= h) {
                    dir = (dir + 1) % 4;
                } else {
                    x = nx, y = ny;
                    --k;
                }
            }
        }
        vector<int> getPos() {
            return {x,y};
        }
        string getDir() {
            return text[dir];
        }
    };
    
  • # 2069. Walking Robot Simulation II
    # https://leetcode.com/problems/walking-robot-simulation-ii/
    
    class Robot:
    
        def __init__(self, width: int, height: int):
            self.rows = width
            self.cols = height
            self.x = 0
            self.y = 0
            self.di = 0
            self.words = ["East", "North", "West", "South"]
            self.cycle = (width + height - 2) * 2
        
        def getNextSteps(self, x, y):
            if self.di == 0:
                return (x + 1, y)
            elif self.di == 1:
                return (x, y + 1)
            elif self.di == 2:
                return (x - 1, y)
            else:
                return (x, y - 1)
    
        def move(self, num: int) -> None:
            num %= self.cycle
            
            if num == 0:
                if self.x == 0 and self.y == 0:
                    self.di = 3
                elif self.x == self.rows - 1 and self.y == 0:
                    self.di = 0
                elif self.x == self.rows - 1 and self.y == self.cols - 1:
                    self.di = 1
                elif self.x == 0 and self.y == self.cols - 1:
                    self.di = 2
                
            for _ in range(num):
                dx, dy = self.getNextSteps(self.x, self.y)
                if not (0 <= dx < self.rows and 0 <= dy < self.cols):
                    self.di = (self.di + 1) % 4
                    dx, dy = self.getNextSteps(self.x, self.y)
                self.x, self.y = dx, dy
    
        def getPos(self) -> List[int]:
            return [self.x, self.y]
    
        def getDir(self) -> str:
            return self.words[self.di]
    
    
    # Your Robot object will be instantiated and called as such:
    # obj = Robot(width, height)
    # obj.move(num)
    # param_2 = obj.getPos()
    # param_3 = obj.getDir()
    
    

Solution 2.

  • // OJ: https://leetcode.com/problems/walking-robot-simulation-ii/
    // Time: O(1) for all
    // Space: O(1)
    class Robot {
        int dir = 0, dirs[4][2] = { {1,0},{0,1},{-1,0},{0,-1} }, w, h, perimeter, x = 0, y = 0;
        string text[4] = {"East","North","West","South"};
        int maxStep() {
            if (dir == 0) return w - 1 - x;
            if (dir == 1) return h - 1 - y;
            if (dir == 2) return x;
            return y;
        }
    public:
        Robot(int width, int height) : w(width), h(height), perimeter(2*(w + h - 2)) {}
        void move(int k) {
            if (k >= perimeter) {
                k %= perimeter;
                if (x == 0 && y == 0 && dir == 0) dir = 3; // Special case: if we are at the beginning (x = 0, y = 0 and facing east), after the round trip, the direction becomes south.
            }
            while (k > 0) {
                int step = min(k, maxStep());
                k -= step;
                auto &[dx, dy] = dirs[dir];
                x += dx * step;
                y += dy * step;
                if (k) dir = (dir + 1) % 4;
            }
        }
        vector<int> getPos() {
            return {x,y};
        }
        string getDir() {
            return text[dir];
        }
    };
    
  • # 2069. Walking Robot Simulation II
    # https://leetcode.com/problems/walking-robot-simulation-ii/
    
    class Robot:
    
        def __init__(self, width: int, height: int):
            self.rows = width
            self.cols = height
            self.x = 0
            self.y = 0
            self.di = 0
            self.words = ["East", "North", "West", "South"]
            self.cycle = (width + height - 2) * 2
        
        def getNextSteps(self, x, y):
            if self.di == 0:
                return (x + 1, y)
            elif self.di == 1:
                return (x, y + 1)
            elif self.di == 2:
                return (x - 1, y)
            else:
                return (x, y - 1)
    
        def move(self, num: int) -> None:
            num %= self.cycle
            
            if num == 0:
                if self.x == 0 and self.y == 0:
                    self.di = 3
                elif self.x == self.rows - 1 and self.y == 0:
                    self.di = 0
                elif self.x == self.rows - 1 and self.y == self.cols - 1:
                    self.di = 1
                elif self.x == 0 and self.y == self.cols - 1:
                    self.di = 2
                
            for _ in range(num):
                dx, dy = self.getNextSteps(self.x, self.y)
                if not (0 <= dx < self.rows and 0 <= dy < self.cols):
                    self.di = (self.di + 1) % 4
                    dx, dy = self.getNextSteps(self.x, self.y)
                self.x, self.y = dx, dy
    
        def getPos(self) -> List[int]:
            return [self.x, self.y]
    
        def getDir(self) -> str:
            return self.words[self.di]
    
    
    # Your Robot object will be instantiated and called as such:
    # obj = Robot(width, height)
    # obj.move(num)
    # param_2 = obj.getPos()
    # param_3 = obj.getDir()
    
    

Discuss

https://leetcode.com/problems/walking-robot-simulation-ii/discuss/1575990/C%2B%2B-handle-round-trip

All Problems

All Solutions