335.self-crossing.go 955 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. func isSelfCrossing(x []int) bool {
  2. // 3 situations for self crossing:
  3. // 1. _____ 0 intersects 3, x[2] <= x[0] && x[1] <= x[3]
  4. // | 1 |
  5. // 2| |0
  6. // `-----+-
  7. // 3 |
  8. //
  9. // 2. _____ 0 intersects (and coincides) 4,
  10. // | 1 | x[1] == x[3] && x[2] <= x[0] + x[4]
  11. // 2| |0
  12. // | |
  13. // |_____^4
  14. // 3
  15. //
  16. // 3. ___ 0 intersects 5,
  17. // | 1 | 5 x[4] <= x[2] && x[1] <= x[3] && x[2] <= x[0] + x[4] && x[3] <= x[1] + x[5]
  18. // | <-+---.
  19. // 2| |0 |4
  20. // |_______|
  21. // 3
  22. //
  23. n := len(x)
  24. if n < 4 {
  25. return false
  26. }
  27. for i := 3; i < n; i++ {
  28. if x[i-1] <= x[i-3] && x[i-2] <= x[i] {
  29. return true
  30. }
  31. if 4 <= i && x[i-3] == x[i-1] && x[i-2] <= x[i-4]+x[i] {
  32. return true
  33. }
  34. if 5 <= i && x[i-1] <= x[i-3] && x[i-4] <= x[i-2] && x[i-3] <= x[i-5]+x[i-1] && x[i-2] <= x[i-4]+x[i] {
  35. return true
  36. }
  37. }
  38. return false
  39. }