给定X轴上的n个点以及这些点之间允许的过渡的列表。查找仅通过这些过渡是否有可能从起点到达终点。
注意:如果在点x1和x2之间存在过渡,则可以从点x移到x1和x2之间的任何中间点,也可以直接移到x2。
例子:
Input : n = 5 ,
Transitions allowed: 0 -> 2
2 -> 4
3 -> 5
Output : YES
Explanation : We can move from 0 to 5 using the
allowed transitions. 0->2->3->5
Input : n = 7 ,
Transitions allowed: 0 -> 4
2 -> 5
6 -> 7
Output : NO
Explanation : We can't move from 0 to 7 as there is
no transition between 5 and 6.
解决此问题的想法是首先根据对中的第一个元素对该列表进行排序。然后从列表的第二对开始遍历,并检查该对的第一个元素是否在上对的第二个元素与当前对的第二个元素之间。此条件用于检查两个连续对之间是否存在路径。
最后,检查我们到达的点是否是目的地点,而我们从其开始的点是否是起点。如果是这样,请打印“是”,否则打印“否”。
C++
// C++ implementation of above idea
#include
using namespace std;
// function to check if it is possible to
// reach the end through given points
bool checkPathPairs(int n, vector > vec)
{
// sort the list of pairs
// according to first element
sort(vec.begin(),vec.end());
int start = vec[0].first;
int end=vec[0].second;
// start traversing from 2nd pair
for (int i=1; i end)
break;
end=max(end,vec[i].second);
}
return (n <= end && start==0);
}
// Driver code
int main()
{
vector > vec;
vec.push_back(make_pair(0,4));
vec.push_back(make_pair(2,5));
vec.push_back(make_pair(6,7));
if (checkPathPairs(7,vec))
cout << "YES";
else
cout << "NO";
return 0;
}
Python3
# Python3 implementation of above idea
# function to check if it is possible to
# reach the end through given points
def checkPathPairs(n: int, vec: list) -> bool:
# sort the list of pairs
# according to first element
vec.sort(key = lambda a: a[0])
start = vec[0][0]
end = vec[0][1]
# start traversing from 2nd pair
for i in range(1, n):
# check if first element of
# current pair is in between
# second element of previous
# and current pair
if vec[i][1] > end:
break
end = max(end, vec[i][1])
return (n <= end and start == 0)
# Driver Code
if __name__ == "__main__":
vec = []
vec.append((0, 4))
vec.append((2, 5))
vec.append((6, 7))
if checkPathPairs(7, vec):
print("YES")
else:
print("NO")
# This code is contributed by
# sanjeev2552
输出:
NO
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。