# Find if it is possible to reach the end through given transitions in C++

C++Server Side ProgrammingProgramming

Suppose we have n points on x-axis and the list of allowed translation between the points. Find if it is possible to reach the end from starting point through these transactions only. So if there is a translation between points x1 and x2, then we can move from point x to any intermediate points between x1 and x2, or directly to x2. So if n = 5. And transactions are 0 to 2, 2 to 4, and 3 to 5. Then output will be YES. There is a path from 0→2→3→5.

We have to sort the list according to the first element of the pairs. Then start from second pair of the list and check if the first element of the pair is in between second element of previous pair and the second element of current pair or not. This condition is used to check if there is a path between two consecutive pairs. At the end we will check whether the point we have reached is the destination point and the point from which we have started is start point. If so, display YES otherwise display NO.

## Example

Live Demo

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
bool isPathPairFound(int n, vector<pair<int, int> > array) {
sort(array.begin(),array.end());
int start_point = array[0].first;
int end_point=array[0].second;
for (int i=1; i<n; i++) {
if (array[i].first > end_point)
break;
end_point=max(end_point,array[i].second);
}
return (n <= end_point && start_point==0);
}
int main() {
vector<pair<int, int> > array;
array.push_back(make_pair(0,2));
array.push_back(make_pair(2,4));
array.push_back(make_pair(3,5));
if (isPathPairFound(5,array))
cout << "Path has found";
else
cout << "NO Path has found";
}

## Output

Path has found
Published on 18-Dec-2019 13:51:41