Print All Paths

You are given a graph with ‘N’ nodes and ‘M’ unidirectional edges. Also you are given two integers ‘S’ and ‘D’ denoting the source and destination. Your task is to find all the paths from ‘S’ to ‘D’.

Note: An ordered set of nodes { S, u1, u2...un, D} is a valid path between ‘S’ and ‘D’, if all nodes along the path are unique.

For example:

For given N = 4, M = 4, S = 0 and D =3.

1

In the above example, the path 0 -> 1 - > 3 is a valid path as all nodes along the path are unique and the path 0 -> 1 -> 2 -> 1 -> 3 is not a valid path because node 1 is visited twice.
Input Format:
The first line contains one positive integer ‘T’, denoting the number of test cases, then ‘T’ test cases follows.

The first line of each test case contains two integers ‘N’ and  ‘M’, denoting the number of nodes and the number of edges.

The next ‘M’ lines of each test case contains two space-separated integers ’u’ and ‘v’, denoting the edge between ‘u’ and ‘v’.

The last line of each test case contains two integers ‘S’ and ‘D’ denoting the source and destination.
Output Format:
The first line of each test case contains an integer ‘N’ , denoting the number of valid paths from ‘S’ to ‘D’.

The next ‘N’ line of each test case contains the all nodes from ‘S’ to ‘D’ along the ‘ith’ path where 1 <= i <= N. 

If there are more than one path then the ith path should be lexicographically smaller than (i + 1) path.

Output of each test case will be printed on 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 <= N <= 5
1 <= M <= 10
0 <= u, v , S, D <= N - 1 

Time Limit: 1 sec.
CodingNinjas
author
2y

1. In this approach we will use BFS (breadth first search) to find all possible paths.

2. We will make a queue which contains the following information :

a) Vector that stores the path up to a certain ...read more

CodingNinjas
author
2y
Backtracking

The idea is very simple: we will perform dfs from a given source node and try out all possible paths using the backtracking concept.

The steps are as follows:

Let ‘allAllPaths(n, m, edges,...read more

Help your peers!
Add answer anonymously...
Nagarro Software 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