Path Reversals

You are given a directed graph and two nodes, ‘S’ and ‘D’, denoting the start and end node. Your task is to find the minimum number of edges that you have to reverse to find the path from nodes 'S' to 'D'.

For example:

graph1

Let's consider 'S' = 0 and 'D' = 4. In the above graph, the path from nodes 0 to 4 can be created by only reversing the edge (0, 5). Hence, the answer is 1.
Input Format:
The first line of input contains an integer ‘T’ representing the number of test cases.

The first line of each test case contains two space-separated integers, ‘N’ and ‘M’, representing the number of nodes and edges in the graph.

The following M lines of the test case contain two space-separated integers, ‘A’ and ‘B’, representing an edge from node ‘A’ to node ‘B’.

The last line of the test case contains two space-separated integers, ‘S’ and ‘D’, denoting the start and end node.
Output Format:
For each test case, print a single integer, i.e., the minimum number of edges to be reversed, so the path exists from ‘S’ to ‘D’.

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
2 <= N <= 10^5
N - 1 <= M <= 10^5
0 <= A, B < N
0 <= S, D < N

Time Limit: 1 sec
AnswerBot
1y

The task is to find the minimum number of edges that need to be reversed in a directed graph to find the path from a start node to an end node.

  • The problem can be solved using graph traversal algorithm...read more

CodingNinjas
author
2y
Bellman-Ford Algorithm

In this approach, we make the graph into a weighted graph. We set the edges’ edge-weight as 0 and add all the reverse edges with weight 1.

We will apply the Bellman-Ford algorithm...read more

CodingNinjas
author
2y
Dijkstra’s Algorithm

In this approach, we make the graph into a weighted graph. We set the edges’ edge-weight as 0 and add all the reverse edges with weight 1.

We will apply Dijkstra’s algorithm on the ...read more

Add answer anonymously...
Myntra Mern Stack Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter