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 trueif your path crosses itself orfalseif it does not.
As you walk in a counter-clockwise spiral, the path can only cross itself in three specific ways, based on the last 4, 5, or 6 moves. By checking these three cases at each step, we can detect any self-crossing efficiently.
classSolution {
publicbooleanisSelfCrossing(int[] x) {
int n = x.length;
for (int i = 3; i < n; i++) {
if (x[i]>= x[i-2]&& x[i-1]<= x[i-3]) returntrue;
if (i >= 4 && x[i-1]== x[i-3]&& x[i]+ x[i-4]>= x[i-2]) returntrue;
if (i >= 5 && x[i-2]>= x[i-4]&& x[i-1]<= x[i-3]&& x[i-1]>= x[i-3]- x[i-5]&& x[i]+ x[i-4]>= x[i-2]&& x[i-3]>= x[i-5]) returntrue;
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funisSelfCrossing(x: IntArray): Boolean {
val n = x.size
for (i in3 until n) {
if (x[i] >= x[i-2] && x[i-1] <= x[i-3]) returntrueif (i >=4&& x[i-1] == x[i-3] && x[i] + x[i-4] >= x[i-2]) returntrueif (i >=5&& x[i-2] >= x[i-4] && x[i-1] <= x[i-3] && x[i-1] >= x[i-3] - x[i-5]
&& x[i] + x[i-4] >= x[i-2] && x[i-3] >= x[i-5]) returntrue }
returnfalse }
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defisSelfCrossing(self, x: list[int]) -> bool:
n = len(x)
for i in range(3, n):
if x[i] >= x[i-2] and x[i-1] <= x[i-3]:
returnTrueif i >=4and x[i-1] == x[i-3] and x[i] + x[i-4] >= x[i-2]:
returnTrueif i >=5and x[i-2] >= x[i-4] and x[i-1] <= x[i-3] and x[i-1] >= x[i-3] - x[i-5] \
and x[i] + x[i-4] >= x[i-2] and x[i-3] >= x[i-5]:
returnTruereturnFalse
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnis_self_crossing(x: Vec<i32>) -> bool {
let n = x.len();
for i in3..n {
if x[i] >= x[i-2] && x[i-1] <= x[i-3] { returntrue; }
if i >=4&& x[i-1] == x[i-3] && x[i] + x[i-4] >= x[i-2] { returntrue; }
if i >=5&& x[i-2] >= x[i-4] && x[i-1] <= x[i-3] && x[i-1] >= x[i-3] - x[i-5]
&& x[i] + x[i-4] >= x[i-2] && x[i-3] >= x[i-5] { returntrue; }
}
false }
}