LeetCode 2069: Walking Robot Simulation II Solution
Master LeetCode problem 2069 (Walking Robot Simulation II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2069. Walking Robot Simulation II
Problem Explanation
Explanation:
- We can maintain the current position and direction of the robot as it moves on the grid.
- For each step, we move in the current direction and check if the next position is within bounds. If not, we change the direction.
- We keep track of the bounds of the grid and update the position and direction accordingly.
- The robot class will have methods to initialize, move, get current position, and get current direction.
Solution Code
class Robot {
int width, height, x, y;
String direction;
public Robot(int width, int height) {
this.width = width;
this.height = height;
this.x = 0;
this.y = 0;
this.direction = "East";
}
public void step(int num) {
for (int i = 0; i < num; i++) {
if (direction.equals("East") && x + 1 < width) {
x++;
} else if (direction.equals("North") && y + 1 < height) {
y++;
} else if (direction.equals("West") && x - 1 >= 0) {
x--;
} else if (direction.equals("South") && y - 1 >= 0) {
y--;
} else {
direction = changeDirection(direction);
i--; // Retry the step
}
}
}
public int[] getPos() {
return new int[]{x, y};
}
public String getDir() {
return direction;
}
private String changeDirection(String dir) {
if (dir.equals("East")) return "North";
if (dir.equals("North")) return "West";
if (dir.equals("West")) return "South";
return "East"; // South
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2069 (Walking Robot Simulation II)?
This page provides optimized solutions for LeetCode problem 2069 (Walking Robot Simulation II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2069 (Walking Robot Simulation II)?
The time complexity for LeetCode 2069 (Walking Robot Simulation II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2069 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2069 in Java, C++, or Python.