LeetCode 858. 镜面反射

有一个特殊的正方形房间,每面墙上都有一面镜子。除西南角以外,每个角落都放有一个接受器,编号为 0, 1,以及 2

正方形房间的墙壁长度为 p,一束激光从西南角射出,首先会与东墙相遇,入射点到接收器 0 的距离为 q 。

返回光线最先遇到的接收器的编号(保证光线最终会遇到一个接收器)。

 

示例:

输入: p = 2, q = 1
输出: 2
解释: 这条光线在第一次被反射回左边的墙时就遇到了接收器 2 。

int isstop(int x,int y,int p){
    if(x == p &&(y == 0 || y == p))
        return 1;
    if(x == 0 && y == p)
        return 1;
    return 0;
}
int isinner(int x,int y,int p){
    if(x >= 0 && x <= p){
        if(y >= 0 && y <= p)
            return 1;
    }
    return 0;
}
int mirrorReflection(int p, int q) {
    int oldx = 0;
    int oldy = 0;
    int newx = p;
    int newy = q;
    int tempx;
    int tempy;
    int flag = 1;
    
    while(isstop(newx,newy,p) == 0){
        if(newx == 0){
            tempx = p;
            if(flag == 1)
                tempy = newy + q;
            else
                tempy = newy - q;
            if(isinner(tempx,tempy,p) == 0){
                tempx = p;
                if(tempy > p)
                    tempy = p - (tempy - p);
                else
                    tempy = -1 * tempy;
                flag = -1 * flag;
            }
        }
        if(newx == p){
            tempx = 0;
            if(flag == 1)
                tempy = newy + q;
            else
                tempy = newy - q;
            if(isinner(tempx,tempy,p) == 0){
                tempx = 0;
                if(tempy > p)
                    tempy = p - (tempy - p);
                else
                    tempy = -1 * tempy;
                flag = -1 * flag;
            }
        }
        newx = tempx;
        newy = tempy;
    }
    if(newx == p && newy == 0)
        return 0;
    else if(newx == p && newy == p)
        return 1;
    return 2;
}


猜你喜欢

转载自blog.csdn.net/curry3030/article/details/80794917