LeetCode 858: Mirror Reflection Solution
Master LeetCode problem 858 (Mirror Reflection), 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.
858. Mirror Reflection
Problem Explanation
Explanation:
To solve this problem, we need to simulate the path of the laser ray as it reflects off the walls of the room. By keeping track of the current position and direction of the ray, we can determine which receptor the ray will hit first.
- Initialize variables representing the current position of the ray and the direction it is moving.
- Simulate the path of the ray by updating its position based on the reflection rules:
- If the ray hits the east wall, it will reflect to the west wall and its vertical position will remain the same.
- If the ray hits the west wall, it will reflect to the east wall and its vertical position will remain the same.
- If the ray hits the north wall, it will reflect to the south wall and its vertical position will be updated based on the distance from the receptor on the east wall.
- Repeat the simulation until the ray hits one of the receptors.
- Return the number of the receptor that the ray hits first. :
Solution Code
class Solution {
public int mirrorReflection(int p, int q) {
int x = 0, y = 0; // current position of the ray
int dirX = p, dirY = q; // direction of the ray
while (true) {
if (x == p && y == 0) return 0; // hit receptor 0
if (x == p && y == p) return 1; // hit receptor 1
if (x == 0 && y == p) return 2; // hit receptor 2
if (dirX > 0) x = p; // hit east wall
else if (dirX < 0) x = 0; // hit west wall
if (dirY > 0) y += dirY; // hit north wall
if (dirY < 0) y += dirY; // hit south wall
if (y == 0 || y == p) dirY = -dirY; // vertical reflection
else dirX = -dirX; // horizontal reflection
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 858 (Mirror Reflection)?
This page provides optimized solutions for LeetCode problem 858 (Mirror Reflection) 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 858 (Mirror Reflection)?
The time complexity for LeetCode 858 (Mirror Reflection) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 858 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 858 in Java, C++, or Python.