335. Path crossing-mathematical induction method (close to the current C language)

335. Path intersection-mathematical induction

You are given an integer array distance.

Starting from the point (0,0) on the XY plane, first move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, and distance[3] meters to the east. , keep moving. In other words, your position will change counterclockwise after each movement.

Determine whether the paths you take intersect. If they intersect, return true; otherwise, return false.
Insert image description here

Input: distance = [2,1,1,2]
Output: true
Insert image description here

Input: distance = [1,2,3,4]
Output: false
Insert image description here
Input: distance = [1,1,1,1]
Output: true

This question seems much more complicated, but in fact there are traces to follow. When we draw the various possible intersection results, we will find that the intersection situations are actually regular, and they only follow the situation of the nearest few lines. Related, the solution code is as follows:

bool isSelfCrossing(int* distance, int distanceSize){
    
    
    for(int i=3;i<distanceSize;i++){
    
    
        if(i==3){
    
    
            if(distance[2]<=distance[0]&&distance[3]>=distance[1]){
    
    
                return true;
            }

        }
        else{
    
    
            if(i==4)
            if(distance[i-1]==distance[i-3]&&distance[i]+distance[i-4]>=distance[i-2]){
    
    
                return true;
            }
            if(i>=5){
    
    
                if(distance[i-1]<=distance[i-3]&&distance[i]>=distance[i-2]){
    
    
                    return true;
                }


if(distance[i-2]>=distance[i-4]&&distance[i-1]<=distance[i-3]&&distance[i-1]+distance[i-5]>=distance[i-3]&&distance[i]+distance[i-4]>=distance[i-2]){
    
    
                    return true;
                }
             }


        }

    }
    return false;
    
}

Guess you like

Origin blog.csdn.net/weixin_43327597/article/details/133201753