Check If Path Exists
You are given a directed and unweighted graph of 'V' vertices and 'E' edges. All edges are given in a 2-dimensional array ‘Edges’ in which ‘Edges[i][0]’ and ‘Edges[i][1]’ contain an edge. Your task is to check if there exists a path from the vertex 'source' to 'destination'.
For Example:
Consider the number of vertices is 4 and number of edges is 3, and the array of edges is:
[ [0, 1]
[1, 2]
[2, 3] ]
there exists one path between 0 and 2, which is 0 -> 1 -> 2. Hence, the answer is 'true'.
Input format :
The first line of input contains an integer ‘T’, the number of test cases.
The first line of each test case contains two space-separated integers, ‘V’, and ‘E’, which denote the number of vertices and edges in the graph.
The next 'E' lines will denote the edges of the graph where every edge is defined by two space-separated integers 'Edges[i][0]’ and 'Edges[i][1]', which signifies an edge from vertex 'Edges[i][0]’ to vertex 'Edges[i][1]’.
The last line of each test case contains two integers, ‘source’ and ‘destination’.
Output Format :
For each test case, print 'true' if there exists a path from vertex 'source' to 'destination'. Otherwise, print 'false'.
Print the output of each test case in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= V, E <= 10 ^ 5
0 <= Edges[i][0], Edges[i][1] < V
0 <= source, destination < V
Time Limit: 1 sec
AnswerBot
1y
The task is to check if there exists a path from a given source vertex to a destination vertex in a directed and unweighted graph.
Read the number of test cases.
For each test case, read the number of v...read more
CodingNinjas
author
2y
Depth First Search
In this approach, we are going to use DFS(Depth-first search). We have to make a visited array isVisited which checks whether the particular node number is visited or not.
Initialize ...read more
CodingNinjas
author
2y
Breadth First Search
In this approach, we are going to use BFS(Breadth-first search). We will take a queue that stores the integer corresponding to node number and take a visited array that checks whet...read more
Add answer anonymously...
Top JUSPAY Front end Developer interview questions & answers
Popular interview questions of Front end Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app