Open In App

Number of times path is crossed

Last Updated : 14 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, you are standing on origin (0, 0). You are allowed to move arr[0] units in the left direction, then arr[1] units in the up direction, and so on, i.e. after every arr[i] distance moved, you can move arr[i+1] in the next clockwise direction. Find the number of times you cross your own traveled path.

Examples:

Input: arr[] = {2, 1, 2, 1, 1}
Output: 1
Explanation: We are starting from coordinate (0, 0) 

  • Our first move will be in a left direction so moving 2 units in the left direction we will be at coordinate (0, -2).
  • On the second move we will move 1 unit in the up direction and come at coordinate (-1, 2).
  • On the third move we will move 2 units in the right direction and come at coordinate (-1, 0).
  • On the fourth move we will move 1 unit in the down direction and come at coordinate (0, 0) and this coordinate is previously visited means at this point we are crossing our own traveled path.
  • On the fifth move we will move 1 unit in the left direction and come at coordinate (0, -1).

Approach: This can be solved with the following idea:

Since there will be only 4 directions to move so, we can find the direction by computing i modulo 4.

  • if i%4=0 we will move in the left direction.
  • if i%4=1 we will move in the up direction.
  • if i%4=2 we will move in the right direction.
  • if i%4=3 we will move in the down direction.

Now, consider our current position as (x, y) in a 2-D matrix. Now, according to the basic logic of a 2-D matrix

  • if we move some distance in the left direction our position will become (x – distance moved, y).
  • if we move some distance in an up direction our position will become (x, y + distance moved).
  • if we move some distance in the right direction our position will become (x + distance moved, y).
  • if we move some distance in a down direction our position will become (x, y – distance moved).

Follow the steps mentioned below to implement the approach:

  • Initialize the set of pairs so that to store the computed coordinates and also declare three variables x, y, and path_crossed, and initialize variables to 0.
  • Insert pair of x and y in the set.
  • We will run a loop from 0 to n-  1, where n is the size of the array.
  • For each i in the range from 0 to n – 1 we will calculate the value of the new coordinate visited by moving arr[i] units (calculation is done using the methods discussed in the approach).
  • Check if the current coordinate is present in the set. If the current coordinate is present then increment the variable path_crossed  by one.
  • Insert the current coordinate in the set.

Below is the implementation of the above approach:

C++14




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Function to check how many times
// path will be crossed
int numberOfTimesPathCrossed(int arr[], int n)
{
 
    // Initialze the set coordinate
    set<pair<int, int> > coordinate;
 
    int x = 0, y = 0, path_crossed = 0;
 
    // Insert the coordinates
    // x and y in set
    coordinate.insert({ x, y });
 
    // For moving in left direction
    for (int i = 0; i < n; i++) {
        if (i % 4 == 0) {
            x = x - arr[i];
        }
 
        // For moving in upwards direction
        else if (i % 4 == 1) {
            y = y + arr[i];
        }
 
        // For moving in right direction
        else if (i % 4 == 2) {
            x = x + arr[i];
        }
 
        // For moving in downwards direction
        else if (i % 4 == 3) {
            y = y - arr[i];
        }
 
        if (coordinate.find({ x, y }) != coordinate.end())
            path_crossed++;
    }
 
    // Inserting the current coordinate
    // into set
    coordinate.insert({ x, y });
 
    return path_crossed;
}
 
// Driver code
int main()
{
 
    int arr[] = { 2, 1, 2, 1, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    int answer = numberOfTimesPathCrossed(arr, n);
 
    cout << answer << endl;
    return 0;
}


Java




import java.io.*;
import java.util.HashSet;
import java.util.Set;
 
public class GFG {
 
    // Function to check how many times
    // path will be crossed
    private static int numberOfTimesPathCrossed(int[] arr) {
 
        // Initialize the set coordinate
        Set<Pair> coordinate = new HashSet<>();
 
        int x = 0, y = 0, path_crossed = 0;
 
        // Insert the coordinates
        // x and y in set
        coordinate.add(new Pair(x, y));
 
        // For moving in left direction
        for (int i = 0; i < arr.length; i++) {
            if (i % 4 == 0) {
                x = x - arr[i];
            }
 
            // For moving in upwards direction
            else if (i % 4 == 1) {
                y = y + arr[i];
            }
 
            // For moving in right direction
            else if (i % 4 == 2) {
                x = x + arr[i];
            }
 
            // For moving in downwards direction
            else if (i % 4 == 3) {
                y = y - arr[i];
            }
 
            if (coordinate.contains(new Pair(x, y))) {
                path_crossed++;
            }
        }
 
        // Inserting the current coordinate
        // into set
        coordinate.add(new Pair(x, y));
 
        return path_crossed;
    }
 
    // Pair class to store x and y coordinates
    private static class Pair {
        int x;
        int y;
 
        Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
 
        // Override equals and hashCode methods for correct Set operations
        @Override
        public boolean equals(Object obj) {
            if (this == obj) return true;
            if (obj == null || getClass() != obj.getClass()) return false;
            Pair pair = (Pair) obj;
            return x == pair.x && y == pair.y;
        }
 
        @Override
        public int hashCode() {
            return Integer.hashCode(x) ^ Integer.hashCode(y);
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        int[] arr = {2, 1, 2, 1, 1};
 
        // Function call
        int answer = numberOfTimesPathCrossed(arr);
 
        System.out.println(answer);
    }
}


Python3




#++ code for the above approach:
 
def number_of_times_path_crossed(arr):
    coordinate = set()  # Set to store visited coordinates
    x, y = 0, 0  # Initial position
    path_crossed = 0  # Counter for crossed paths
 
    coordinate.add((x, y))  # Insert the initial coordinate (0, 0) into the set
 
    # Traverse the array of directions and distances
    for i in range(len(arr)):
        if i % 4 == 0# Moving left
            x -= arr[i]
        elif i % 4 == 1# Moving upwards
            y += arr[i]
        elif i % 4 == 2# Moving right
            x += arr[i]
        elif i % 4 == 3# Moving downwards
            y -= arr[i]
 
        if (x, y) in coordinate:  # Check if the current coordinate has been visited before
            path_crossed += 1
 
        coordinate.add((x, y))  # Insert the current coordinate into the set
 
    return path_crossed
 
arr = [2, 1, 2, 1, 1]
answer = number_of_times_path_crossed(arr)
print(answer)


C#




// C# code for the above approach:
 
using System;
using System.Collections.Generic;
 
class Program
{
    // Function to check how many times
    // path will be crossed
    static int NumberOfTimesPathCrossed(int[] arr, int n)
    {
        // Initialize the set coordinate
        HashSet<Tuple<int, int>> coordinate = new HashSet<Tuple<int, int>>();
 
        int x = 0, y = 0, pathCrossed = 0;
 
        // Insert the coordinates
        // x and y in set
        coordinate.Add(new Tuple<int, int>(x, y));
 
        // For moving in left direction
        for (int i = 0; i < n; i++)
        {
            if (i % 4 == 0)
            {
                x = x - arr[i];
            }
            // For moving in upwards direction
            else if (i % 4 == 1)
            {
                y = y + arr[i];
            }
            // For moving in right direction
            else if (i % 4 == 2)
            {
                x = x + arr[i];
            }
            // For moving in downwards direction
            else if (i % 4 == 3)
            {
                y = y - arr[i];
            }
 
            if (coordinate.Contains(new Tuple<int, int>(x, y)))
                pathCrossed++;
        }
 
        // Inserting the current coordinate
        // into set
        coordinate.Add(new Tuple<int, int>(x, y));
 
        return pathCrossed;
    }
 
    // Driver code
    static void Main(string[] args)
    {
        int[] arr = { 2, 1, 2, 1, 1 };
        int n = arr.Length;
 
        // Function call
        int answer = NumberOfTimesPathCrossed(arr, n);
 
        Console.WriteLine(answer);
    }
}


Javascript




// Function to check how many times
// path will be crossed
function numberOfTimesPathCrossed(arr) {
     
    // Initialze the set coordinate
    let coordinate = new Set();
    let x = 0, y = 0, path_crossed = 0;
     
    // Insert the coordinates
    // x and y in set
    coordinate.add(`${x},${y}`);
     
     
    // For moving in left direction   
    for (let i = 0; i < arr.length; i++) {
        if (i % 4 === 0) {
            x = x - arr[i];
        }
         
        // For moving in upwards direction
        else if (i % 4 === 1) {
            y = y + arr[i];
        }
        // For moving in right direction
        else if (i % 4 === 2) {
            x = x + arr[i];
        }
         
        // For moving in downwards direction
        else if (i % 4 === 3) {
            y = y - arr[i];
        }
         
         
        if (coordinate.has(`${x},${y}`)) {
            path_crossed++;
        }
    }
     
    // Inserting the current coordinate
    // into set
    coordinate.add(`${x},${y}`);
    return path_crossed;
}
 
// Driver code
let arr = [2, 1, 2, 1, 1];
let answer = numberOfTimesPathCrossed(arr);
console.log(answer);


Output

1

Time Complexity: O(N*log(N))
Auxiliary Space: O(N2)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads