Leetcode 2069: Walking Robot Simulation II

grid47
grid47
Exploring patterns and algorithms
Apr 14, 2024 7 min read

A robot is placed on a grid and initially faces East. It is instructed to move forward by a specified number of steps. If the robot attempts to move out of bounds, it turns 90 degrees counterclockwise and tries again. The task is to implement a class for the robot that can handle these movements and return its current position and direction.
Problem
Approach
Steps
Complexity
Input: The input consists of two parts: the dimensions of the grid and the instructions for the robot's movements. The robot starts at position (0, 0), facing East.
Example:
Constraints:
Output: The output includes the robot's current position in the grid (as a two-element array [x, y]) and its current facing direction.
Example:
Constraints:
Goal: To move the robot based on instructions and handle boundary conditions with turning.
Steps:
• Initialize the grid dimensions and robot's starting position and direction.
• Implement logic to move the robot one step at a time, checking for boundary conditions and turning the robot if necessary.
• Ensure that the robot's position and direction are correctly updated after each movement instruction.
Goal: The robot is constrained within a grid of width and height. At most 10^4 operations (steps, getPos, and getDir) can be performed.
Steps:
Assumptions:
• The grid's width and height will always be at least 2.
• The robot will always start at position (0, 0) and face East.
Input: Robot robot = new Robot(6, 3);
Explanation: Here, the robot is initialized on a 6x3 grid, starting at position (0, 0), facing East.

Input: robot.step(2); robot.getPos(); robot.getDir();
Explanation: The robot moves two steps East and is now at position (2, 0), facing East.

Input: robot.step(2); robot.getPos(); robot.getDir();
Explanation: After moving two more steps East, the robot is at position (4, 0), still facing East.

Input: robot.step(2); robot.step(1); robot.step(4); robot.getPos(); robot.getDir();
Explanation: After additional steps, the robot moves in different directions, including turning when hitting boundaries, eventually reaching position (1, 2) facing West.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus