LeetCode 858: Mirror Reflection

Problem Description

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.

  1. Initialize variables representing the current position of the ray and the direction it is moving.
  2. 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.
  3. Repeat the simulation until the ray hits one of the receptors.
  4. Return the number of the receptor that the ray hits first. :

Solutions

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
        }
    }
}

Loading editor...