335. Self Crossing
You are given an array of integers distance.
You start at the point (0, 0) on an X-Y plane, and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.
Return true if your path crosses itself or false if it does not.
Example 1:
Example 2:
Example 3:
Constraints:
- 1 < = d i s t a n c e . l e n g t h < = 1 0 5 1 <= distance.length <= 10^5 1<=distance.length<=105
- 1 < = d i s t a n c e [ i ] < = 1 0 5 1 <= distance[i] <= 10^5 1<=distance[i]<=105
From: LeetCode
Link: 335. Self Crossing
Solution:
Ideas:
- Case 1: When the current move makes a cross with the move 2 steps before it.
- Case 2: When the current move makes a cross by touching the line made 3 steps before.
- Case 3: When the current move crosses by overlapping the line made 4 steps before.
Code:
bool isSelfCrossing(int* distance, int distanceSize) {
if (distanceSize < 4) {
return false;
}
for (int i = 3; i < distanceSize; i++) {
// Case 1: Fourth line crosses the first line
if (distance[i] >= distance[i - 2] && distance[i - 1] <= distance[i - 3]) {
return true;
}
// Case 2: Fifth line meets the first line
if (i >= 4 && distance[i - 1] == distance[i - 3] && distance[i] + distance[i - 4] >= distance[i - 2]) {
return true;
}
// Case 3: Sixth line crosses the first line
if (i >= 5 && distance[i - 2] >= distance[i - 4] && distance[i] + distance[i - 4] >= distance[i - 2] &&
distance[i - 1] <= distance[i - 3] && distance[i - 1] + distance[i - 5] >= distance[i - 3]) {
return true;
}
}
return false;
}