Description Link to heading

335. Self Crossing (Hard)

Solution Link to heading

We can simulate the movement of the robot and consider the possible collisions with other tracks. For example, when moving north, the robot may intersect with tracks moving west, east, or north. Similarly, when moving west, the robot may collide with tracks moving north, south, or west. We can continue this process for other directions as well.

For instance, when moving west, we can consider the conditions for collisions with tracks moving north, south, or west.

Code Link to heading

class Solution {
  public:
    bool isSelfCrossing(vector<int> &distance) {
        int n = distance.size();
        if (n <= 3) {
            return 0;
        }
        for (int i = 3; i < n; ++i) {
            cout << i << endl;
            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]) || (distance[i] >= distance[i - 2] && distance[i - 1] <= distance[i - 3])) {
                    return true;
                }
            } else {
                if ((distance[i - 1] <= distance[i - 3] && distance[i] >= distance[i - 2]) || (distance[i] + distance[i - 4] >= distance[i - 2] && distance[i - 1] + distance[i - 5] >= distance[i - 3] && distance[i - 3] > distance[i - 5] && distance[i - 2] > distance[i - 4] && distance[i - 1] <= distance[i - 3]) || (distance[i - 1] == distance[i - 3] && distance[i] + distance[i - 4] >= distance[i - 2])) {
                    return true;
                }
            }
        }
        return false;
    }
};