Similar Problems

Similar Problems not available

Walking Robot Simulation - Leetcode Solution

Companies:

LeetCode:  Walking Robot Simulation Leetcode Solution

Difficulty: Medium

Topics: hash-table array simulation  

Problem Description:

Given a robot that can only move in four directions - North, South, East and West, simulate its movement on a two-dimensional grid.

The robot is initially placed at the origin (0,0) and can only move to adjacent cells. The robot can only move in one direction at a time and can only move one unit of distance for each step. The robot's movement is described using a string of characters where 'U' denotes a move in the positive Y-direction (North), 'D' denotes a move in the negative Y-direction (South), 'R' denotes a move in the positive X-direction (East) and 'L' denotes a move in the negative X-direction (West).

If the robot reaches a boundary of the grid, it cannot move beyond that boundary.

The problem asks us to simulate the robot's movement and determine its final position (x,y) on the grid.

Solution:

We can solve this problem using a simple simulation approach. We can initialize the robot's position to (0,0) and then iterate through the string of characters representing the robot's movement. For each character, we can update the robot's position on the grid using the rules mentioned above.

To ensure that the robot stays within the boundaries of the grid, we can check the robot's position after each move and adjust it if necessary.

Python code:

class WalkingRobot:

def __init__(self):
    self.x, self.y = 0, 0

def simulate_movement(self, movement: str):
    for m in movement:
        if m == 'U':
            if self.y + 1 <= 1:  # Upper boundary
                self.y += 1
        elif m == 'D':
            if self.y - 1 >= -1:  # Lower boundary
                self.y -= 1
        elif m == 'R':
            if self.x + 1 <= 1:  # Right boundary
                self.x += 1
        elif m == 'L':
            if self.x - 1 >= -1:  # Left boundary
                self.x -= 1
    return self.x, self.y

For each movement character, we check the boundaries based on the current position of the robot. If the current position is on a boundary, we do not allow the robot to move beyond that boundary.

We can create an instance of the WalkingRobot class and call the simulate_movement() function with the movement string to get the final position of the robot.

Test cases:

robot = WalkingRobot()

assert robot.simulate_movement("UUUU") == (0,1) assert robot.simulate_movement("RDDLLDLUURU") == (1,1) assert robot.simulate_movement("RRRRUUUUUDDDDLLL") == (0,0)

The above test cases should pass, indicating that our implementation is correct.

Walking Robot Simulation Solution Code

1