Print all paths from a given source to a destination
Last Updated :
22 Apr, 2025
Given a directed acyclic graph, a source vertex src and a destination vertex dest, print all paths from given src to dest.
Examples:
Input: V = 4, edges[ ][ ] = [[0, 1], [1, 2], [1, 3], [2, 3]], src = 0, dest = 3
Output: [[0, 1, 2, 3], [0, 1, 3]]
Explanation: There are two ways to reach at 3 from 0. These are: 0 -> 1 -> 3 and 0 -> 1 -> 2 -> 3.
Input: V = 4, edges[ ][ ] = [[0, 3], [0, 1], [1, 3], [2, 1], [2, 0]], src = 2, dest = 3
Output: [[2, 1, 3], [2, 0, 3], [2, 0, 1, 3]]
Explanation: There are three ways to reach at 3 from 2. These are: 2 -> 1 -> 3, 2 -> 0 -> 3 and 2 -> 0 -> 1 -> 3.

[Approach 1] Using DFS
The main idea uses DFS to explore all paths from the source to the destination in a directed graph. It recursively builds paths, stores them when the destination is reached, and backtracks to explore alternative routes.
[GFGTABS]
C++
// C++ Program to print all paths
// from source to destination
#include <iostream>
#include <vector>
using namespace std;
void dfs(int src, int dest, vector<vector<int>> &graph, vector<int> &path,
vector<vector<int>> &allPaths){
// Add the current vertex to the path
path.push_back(src);
// Store the path when destination is reached
if (src == dest){
allPaths.push_back(path);
}
else{
for (int adj_node:graph[src]){
dfs(adj_node, dest, graph, path, allPaths);
}
}
// remove the current vertex from the path
path.pop_back();
}
vector<vector<int>> findPaths(int v, vector<vector<int>> &edges, int src, int dest){
vector<vector<int>> graph(v);
// Build the graph from edges
for (const auto &edge : edges){
graph[edge[0]].push_back(edge[1]);
}
vector<vector<int>> allPaths;
vector<int> path;
dfs(src, dest, graph, path, allPaths);
return allPaths;
}
int main(){
vector<vector<int>> edges = {{0, 3}, {0, 1}, {1, 3}, {2, 0}, {2, 1}};
int src = 2, dest = 3;
int v = 4;
vector<vector<int>> paths = findPaths(v, edges, src, dest);
for (const auto &path : paths){
for (int vtx : path){
cout << vtx << " ";
}
cout << endl;
}
return 0;
}
Java
// Java Program to print all paths
// from source to destination
import java.util.ArrayList;
import java.util.List;
class GfG {
static ArrayList<ArrayList<Integer>> dfs(int src, int dest,
List<List<Integer>> graph, ArrayList<Integer> path,
ArrayList<ArrayList<Integer>> allPaths) {
// Add the current vertex to the path
path.add(src);
// Store the path when destination is reached
if (src == dest) {
allPaths.add(new ArrayList<>(path));
} else {
for (int adjNode : graph.get(src)) {
dfs(adjNode, dest, graph, path, allPaths);
}
}
// remove the current vertex from the path
path.remove(path.size() - 1);
return allPaths;
}
static ArrayList<ArrayList<Integer>> findPaths(int v, int[][] edges,
int src, int dest) {
List<List<Integer>> graph = new ArrayList<>();
// Build the graph from edges
for (int i = 0; i < v; i++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
}
ArrayList<ArrayList<Integer>> allPaths = new ArrayList<>();
ArrayList<Integer> path = new ArrayList<>();
dfs(src, dest, graph, path, allPaths);
return allPaths;
}
public static void main(String[] args) {
int[][] edges = {{0, 3}, {0, 1}, {1, 3}, {2, 0}, {2, 1}};
int src = 2, dest = 3;
int v = 4;
ArrayList<ArrayList<Integer>> paths = findPaths(v, edges, src, dest);
for (ArrayList<Integer> path : paths) {
for (int vtx : path) {
System.out.print(vtx + " ");
}
System.out.println();
}
}
}
Python
# Python Program to print all paths
# from source to destination
def dfs(src, dest, graph, path, allPaths):
# Add the current vertex to the path
path.append(src)
# Store the path when destination is reached
if src == dest:
allPaths.append(path.copy())
else:
for adj_node in graph[src]:
dfs(adj_node, dest, graph, path, allPaths)
# remove the current vertex from the path
path.pop()
def findPaths(v, edges, src, dest):
graph = [[] for _ in range(v)]
# Build the graph from edges
for edge in edges:
graph[edge[0]].append(edge[1])
allPaths = []
path = []
dfs(src, dest, graph, path, allPaths)
return allPaths
if __name__ == "__main__":
edges = [[0, 3], [0, 1], [1, 3], [2, 0], [2, 1]]
src = 2
dest = 3
v = 4
paths = findPaths(v, edges, src, dest)
for path in paths:
for vtx in path:
print(vtx, end=" ")
print()
C#
using System;
using System.Collections.Generic;
class GfG {
static void dfs(int src, int dest, int[,] graph, bool[] visited,
List<int> path,
List<List<int>> allPaths) {
// Add the current vertex to the path
path.Add(src);
// If destination is reached, store the path
if (src == dest) {
allPaths.Add(new List<int>(path));
}
else {
// Recurse for all adjacent vertices
for (int adjNode = 0; adjNode < graph.GetLength(0); adjNode++) {
if (graph[src, adjNode] == 1 && !visited[adjNode]) {
visited[adjNode] = true;
dfs(adjNode, dest, graph, visited, path, allPaths);
visited[adjNode] = false;
}
}
}
// Remove the current vertex from path
path.RemoveAt(path.Count - 1);
}
public static List<List<int>> FindPaths(int v, int[,] edges, int src, int dest) {
int[,] graph = new int[v, v];
// Build the graph from edges
for (int i = 0; i < edges.GetLength(0); i++) {
int u = edges[i, 0];
int vtx = edges[i, 1];
// mark the edge between u and vtx
graph[u, vtx] = 1;
}
bool[] visited = new bool[v];
List<int> path = new List<int>();
List<List<int>> allPaths = new List<List<int>>();
visited[src] = true;
dfs(src, dest, graph, visited, path, allPaths);
return allPaths;
}
public static void Main(string[] args) {
int[,] edges = new int[,]
{
{ 0, 3 }, { 0, 1 }, { 1, 3 }, { 2, 0 }, { 2, 1 }
};
int src = 2, dest = 3;
int v = 4;
List<List<int>> paths = FindPaths(v, edges, src, dest);
foreach (List<int> path in paths) {
foreach (int vtx in path) {
Console.Write(vtx + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// JavaScript Program to print all paths
// from source to destination
function dfs(src, dest, graph, path, allPaths){
// Add the current vertex to the path
path.push(src);
// Store the path when destination is reached
if (src === dest) {
allPaths.push([...path ]);
}
else {
for (let adjNode of graph[src]) {
dfs(adjNode, dest, graph, path, allPaths);
}
}
// remove the current vertex from the path
path.pop();
}
function findPaths(v, edges, src, dest){
let graph = Array.from({length : v}, () => []);
// Build the graph from edges
for (let edge of edges) {
graph[edge[0]].push(edge[1]);
}
let allPaths = [];
let path = [];
dfs(src, dest, graph, path, allPaths);
return allPaths;
}
// Driver Code
const edges =
[ [ 0, 3 ], [ 0, 1 ], [ 1, 3 ], [ 2, 0 ], [ 2, 1 ] ];
const src = 2;
const dest = 3;
const v = 4;
const paths = findPaths(v, edges, src, dest);
for (const path of paths) {
console.log(path.join(" "));
}
[/GFGTABS]
Output
2 0 3
2 0 1 3
2 1 3
Time Complexity: O(2V ), where V is number of vertices. There can be at most 2V paths in the graph
Auxiliary Space: O(V + E)
[Approach 2] Using BFS
The main idea is to use Breadth-First Search (BFS) to find all paths from a source to a destination in a directed graph. It uses a queue to explore all possible paths level by level. Each path is stored and extended by adding adjacent nodes, and when the destination is reached, the current path is added to the result.
[GFGTABS]
C++
// C++ Program to find all paths
// from source to destination in a directed graph
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
vector<vector<int>> findPaths(int v, vector<vector<int>> &edges,
int src, int dest) {
vector<vector<int>> graph(v);
// Build the graph from edges
for (const auto &edge : edges) {
graph[edge[0]].push_back(edge[1]);
}
vector<vector<int>> allPaths;
queue<vector<int>> q;
// Initialize queue with the starting path
q.push({src});
while (!q.empty()) {
vector<int> path = q.front();
q.pop();
int current = path.back();
// If destination is reached, store the path
if (current == dest) {
allPaths.push_back(path);
}
// Explore all adjacent vertices
for (int adj : graph[current]) {
vector<int> newPath = path;
newPath.push_back(adj);
q.push(newPath);
}
}
return allPaths;
}
int main() {
vector<vector<int>> edges = {{0, 3}, {0, 1}, {1, 3}, {2, 0}, {2, 1}};
int src = 2, dest = 3;
int v = 4;
// Find all paths from source to destination
vector<vector<int>> paths = findPaths(v, edges, src, dest);
// Print all the paths
for (const auto &path : paths) {
for (int vtx : path) {
cout << vtx << " ";
}
cout << endl;
}
return 0;
}
Java
// Java Program to find all paths
// from source to destination in a directed graph
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class GfG {
public static ArrayList<ArrayList<Integer>> findPaths(int v, int[][] edges, int src, int dest) {
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i < v; i++) {
graph.add(new ArrayList<>());
}
// Build the graph from edges
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
}
ArrayList<ArrayList<Integer>> allPaths = new ArrayList<>();
Queue<ArrayList<Integer>> q = new LinkedList<>();
// Initialize queue with the starting path
ArrayList<Integer> initialPath = new ArrayList<>();
initialPath.add(src);
q.add(initialPath);
while (!q.isEmpty()) {
ArrayList<Integer> path = q.poll();
int current = path.get(path.size() - 1);
// If destination is reached, store the path
if (current == dest) {
allPaths.add(new ArrayList<>(path));
}
// Explore all adjacent vertices
for (int adj : graph.get(current)) {
ArrayList<Integer> newPath = new ArrayList<>(path);
newPath.add(adj);
q.add(newPath);
}
}
return allPaths;
}
public static void main(String[] args) {
int[][] edges = {{0, 3}, {0, 1}, {1, 3}, {2, 0}, {2, 1}};
int src = 2, dest = 3;
int v = 4;
// Find all paths from source to destination
ArrayList<ArrayList<Integer>> paths = findPaths(v, edges, src, dest);
// Print all the paths
for (ArrayList<Integer> path : paths) {
for (int vtx : path) {
System.out.print(vtx + " ");
}
System.out.println();
}
}
}
Python
# Python Program to find all paths
# from source to destination in a directed graph
from collections import deque
def findPaths(v, edges, src, dest):
graph = [[] for _ in range(v)]
# Build the graph from edges
for edge in edges:
graph[edge[0]].append(edge[1])
allPaths = []
q = deque()
# Initialize queue with the starting path
q.append([src])
while q:
path = q.popleft()
current = path[-1]
# If destination is reached, store the path
if current == dest:
allPaths.append(path)
# Explore all adjacent vertices
for adj in graph[current]:
newPath = list(path)
newPath.append(adj)
q.append(newPath)
return allPaths
if __name__ == "__main__":
edges = [[0, 3], [0, 1], [1, 3], [2, 0], [2, 1]]
src = 2
dest = 3
v = 4
# Find all paths from source to destination
paths = findPaths(v, edges, src, dest)
# Print all the paths
for path in paths:
for vtx in path:
print(vtx, end=" ")
print()
C#
// C# Program to find all paths
// from source to destination in a directed graph
using System;
using System.Collections.Generic;
class GfG {
public static List<List<int>>
findPaths(int v, int[, ] edges, int src, int dest) {
List<List<int> > graph = new List<List<int> >();
for (int i = 0; i < v; i++) {
graph.Add(new List<int>());
}
// Build the graph from edges
int edgeCount = edges.GetLength(0);
for (int i = 0; i < edgeCount; i++) {
int u = edges[i, 0];
int vtx = edges[i, 1];
graph[u].Add(vtx);
}
List<List<int> > allPaths = new List<List<int> >();
Queue<List<int> > q = new Queue<List<int> >();
// Initialize queue with the starting path
q.Enqueue(new List<int>{ src });
while (q.Count > 0) {
List<int> path = q.Dequeue();
int current = path[path.Count - 1];
// If destination is reached, store the path
if (current == dest) {
allPaths.Add(new List<int>(path));
}
// Explore all adjacent vertices
foreach(int adj in graph[current]) {
List<int> newPath = new List<int>(path);
newPath.Add(adj);
q.Enqueue(newPath);
}
}
return allPaths;
}
static void Main(){
int[, ] edges = {
{ 0, 3 }, { 0, 1 }, { 1, 3 }, { 2, 0 }, { 2, 1 }
};
int src = 2, dest = 3;
int v = 4;
// Find all paths from source to destination
var paths = findPaths(v, edges, src, dest);
// Print all the paths
foreach(var path in paths) {
Console.WriteLine(string.Join(" ", path));
}
}
}
JavaScript
// JavaScript Program to find all paths
// from source to destination in a directed graph
function findPaths(v, edges, src, dest) {
const graph = Array.from({ length: v }, () => []);
// Build the graph from edges
for (const edge of edges) {
graph[edge[0]].push(edge[1]);
}
const allPaths = [];
const q = [];
// Initialize queue with the starting path
q.push([src]);
while (q.length > 0) {
const path = q.shift();
const current = path[path.length - 1];
// If destination is reached, store the path
if (current === dest) {
allPaths.push(path);
}
// Explore all adjacent vertices
for (const adj of graph[current]) {
const newPath = [...path, adj];
q.push(newPath);
}
}
return allPaths;
}
// Driver Code
const edges = [[0, 3], [0, 1], [1, 3], [2, 0], [2, 1]];
const src = 2, dest = 3;
const v = 4;
// Find all paths from source to destination
const paths = findPaths(v, edges, src, dest);
// Print all the paths
for (const path of paths) {
console.log(path.join(' '));
}
[/GFGTABS]
Output
2 0 3
2 1 3
2 0 1 3
Time Complexity: O(2V), where V is number of vertices. There can be at most 2V paths in the graph
Auxiliary Space: O(V + E)
Similar Reads
Backtracking Algorithm
Backtracking algorithms are like problem-solving strategies that help explore different options to find the best solution. They work by trying out different paths and if one doesn't work, they backtrack and try another until they find the right one. It's like solving a puzzle by testing different pi
4 min read
Introduction to Backtracking
Backtracking is like trying different paths, and when you hit a dead end, you backtrack to the last choice and try a different route. In this article, we'll explore the basics of backtracking, how it works, and how it can help solve all sorts of challenging problems. It's like a method for finding t
7 min read
Difference between Backtracking and Branch-N-Bound technique
Algorithms are the methodical sequence of steps which are defined to solve complex problems. In this article, we will see the difference between two such algorithms which are backtracking and branch and bound technique. Before getting into the differences, lets first understand each of these algorit
4 min read
What is the difference between Backtracking and Recursion?
What is Recursion?The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Real Life ExampleImagine we have a set of boxes, each containing a smaller box. To find an item, we open the outermost box and cont
4 min read
Standard problems on backtracking
The Knight's tour problem
Given an n à n chessboard with a Knight starting at the top-left corner (position (0, 0)). The task is to determine a valid Knight's Tour where where the Knight visits each cell exactly once following the standard L-shaped moves of a Knight in chess.If a valid tour exists, print an n à n grid where
10 min read
Rat in a Maze
Given an n x n binary matrix representing a maze, where 1 means open and 0 means blocked, a rat starts at (0, 0) and needs to reach (n - 1, n - 1). The rat can move up (U), down (D), left (L), and right (R), but: It cannot visit the same cell more than once.It can only move through cells with value
9 min read
N Queen Problem
Given an integer n, the task is to find the solution to the n-queens problem, where n queens are placed on an n*n chessboard such that no two queens can attack each other. The N Queen is the problem of placing N chess queens on an NÃN chessboard so that no two queens attack each other. For example,
15+ min read
Subset Sum Problem using Backtracking
Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum. Examples:Â Input:Â set[] = {1,2,1}, sum = 3Output:Â [1,2],[2,1]Explanation:Â There are subsets [1,2],[2,1] with sum 3. Input:Â set[] = {3, 34, 4, 12, 5, 2}, sum =
8 min read
M-Coloring Problem
Given an edges of graph and a number m, the your task is to find weather is possible to color the given graph with at most m colors such that no two adjacent vertices of the graph are colored with the same color. Examples Input: V = 4, edges[][] = [[0, 1], [0, 2], [1, 3], [2, 3]], m = 3Output: trueE
13 min read
Hamiltonian Cycle
What is Hamiltonian Cycle?Hamiltonian Cycle or Circuit in a graph G is a cycle that visits every vertex of G exactly once and returns to the starting vertex. If graph contains a Hamiltonian cycle, it is called Hamiltonian graph otherwise it is non-Hamiltonian.Finding a Hamiltonian Cycle in a graph i
15+ min read
Algorithm to Solve Sudoku | Sudoku Solver
Given an incomplete Sudoku in the form of matrix mat[][] of order 9*9, the task is to complete the Sudoku.A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row.Each of the digits 1-9 must occur exactly once in each column.Each of the di
15+ min read
Magnet Puzzle
The puzzle game Magnets involves placing a set of domino-shaped magnets (or electrets or other polarized objects) in a subset of slots on a board so as to satisfy a set of constraints. For example, the puzzle on the left has the solution shown on the right: Â Each slot contains either a blank entry
15+ min read
Remove Invalid Parentheses
An expression will be given which can contain open and close parentheses and optionally some characters, No other operator will be there in string. We need to remove minimum number of parentheses to make the input string valid. If more than one valid output are possible removing same number of paren
9 min read
A backtracking approach to generate n bit Gray Codes
Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit) Examples: Input : 2 Output : 0 1 3 2Explanation : 00 - 001 - 111 - 310 - 2Input : 3 Output : 0 1 3 2 6 7 5 4 We have discussed an approach in Generate n-
6 min read
Permutations of given String
Given a string s, the task is to return all permutations of a given string in lexicographically sorted order. Note: A permutation is the rearrangement of all the elements of a string. Duplicate arrangement can exist. Examples: Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CAB", "CBA" Input: s
5 min read
Easy Problems on Backtracking
Print all subsets of a given Set or Array
Given an array arr of size n, your task is to print all the subsets of the array in lexicographical order. A subset is any selection of elements from an array, where the order does not matter, and no element appears more than once. It can include any number of elements, from none (the empty subset)
12 min read
Check if a given string is sum-string
Given a string of digits, determine whether it is a âsum-stringâ. A string S is called a sum-string if the rightmost substring can be written as the sum of two substrings before it and the same is recursively true for substrings before it. Examples: â12243660â is a sum string. Explanation : 24 + 36
12 min read
Count all possible Paths between two Vertices
Count the total number of ways or paths that exist between two vertices in a directed graph. These paths don't contain a cycle, the simple enough reason is that a cycle contains an infinite number of paths and hence they create a problem Examples: For the following Graph: Input: Count paths between
9 min read
Find all distinct subsets of a given set using BitMasking Approach
Given an array of integers arr[], The task is to find all its subsets. The subset can not contain duplicate elements, so any repeated subset should be considered only once in the output. Examples: Input: S = {1, 2, 2}Output: {}, {1}, {2}, {1, 2}, {2, 2}, {1, 2, 2}Explanation: The total subsets of gi
12 min read
Find if there is a path of more than k length from a source
Given a graph, a source vertex in the graph and a number k, find if there is a simple path (without any cycle) starting from given source and ending at any other vertex such that the distance from source to that vertex is atleast 'k' length. Example: Input : Source s = 0, k = 58 Output : True There
15 min read
Print all paths from a given source to a destination
Given a directed acyclic graph, a source vertex src and a destination vertex dest, print all paths from given src to dest. Examples: Input: V = 4, edges[ ][ ] = [[0, 1], [1, 2], [1, 3], [2, 3]], src = 0, dest = 3Output: [[0, 1, 2, 3], [0, 1, 3]]Explanation: There are two ways to reach at 3 from 0. T
12 min read
Print all possible strings that can be made by placing spaces
Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. Input: str[] = "ABC" Output: ABC AB C A BC A B C Source: Amazon Interview Experience | Set 158, Round 1, Q 1. Recommended PracticePermutation with SpacesTry It! The idea is to use
11 min read
Medium prblems on Backtracking
Tug of War
Given a set of n integers, divide the set in two subsets of n/2 sizes each such that the absolute difference of the sum of two subsets is as minimum as possible. If n is even, then sizes of two subsets must be strictly n/2 and if n is odd, then size of one subset must be (n-1)/2 and size of other su
15 min read
8 queen problem
The eight queens problem is the problem of placing eight queens on an 8Ã8 chessboard such that none of them attack one another (no two are in the same row, column, or diagonal). More generally, the n queens problem places n queens on an nÃn chessboard. There are different solutions for the problem.
8 min read
Combination Sum
Given an array of distinct integers arr[] and an integer target, the task is to find a list of all unique combinations of array where the sum of chosen element is equal to target. Note: The same number may be chosen from array an unlimited number of times. Two combinations are unique if the frequenc
8 min read
Warnsdorff's algorithm for Knightâs tour problem
Problem : A knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each square exactly once. Following is an example path followed by Knight to cover all the cells. The below grid represents a chessboard with 8 x 8 cells. Numbers in cells indica
15+ min read
Find paths from corner cell to middle cell in maze
Given a square maze represented by a matrix mat[][] of positive numbers, the task is to find all paths from all four corner cells to the middle cell. From any cell mat[i][j] with value n, you are allowed to move exactly n steps in one of the four cardinal directionsâNorth, South, East, or West. That
14 min read
Maximum number possible by doing at-most K swaps
Given a string s and an integer k, the task is to find the maximum possible number by performing swap operations on the digits of s at most k times. Examples: Input: s = "7599", k = 2Output: 9975Explanation: Two Swaps can make input 7599 to 9975. First swap 9 with 5 so number becomes 7995, then swap
15 min read
Rat in a Maze with multiple steps or jump allowed
You are given an n à n maze represented as a matrix. The rat starts from the top-left corner (mat[0][0]) and must reach the bottom-right corner (mat[n-1][n-1]). The rat can move forward (right) or downward.A 0 in the matrix represents a dead end, meaning the rat cannot step on that cell.A non-zero v
11 min read
N Queen in O(n) space
Given an integer n, the task is to find the solution to the n-queens problem, where n queens are placed on an n*n chessboard such that no two queens can attack each other. The N Queen is the problem of placing N chess queens on an NÃN chessboard so that no two queens attack each other. For example,
7 min read
Hard problems on Backtracking
Power Set in Lexicographic order
This article is about generating Power set in lexicographical order. Examples : Input : abcOutput : a ab abc ac b bc cThe idea is to sort array first. After sorting, one by one fix characters and recursively generates all subsets starting from them. After every recursive call, we remove last charact
9 min read
Word Break Problem using Backtracking
Given a non-empty sequence s and a dictionary dict[] containing a list of non-empty words, the task is to return all possible ways to break the sentence in individual dictionary words.Note: The same word in the dictionary may be reused multiple times while breaking.Examples: Input: s = âcatsanddogâ
8 min read
Partition of a set into K subsets with equal sum
Given an integer array arr[] and an integer k, the task is to check if it is possible to divide the given array into k non-empty subsets of equal sum such that every array element is part of a single subset. Examples: Input: arr[] = [2, 1, 4, 5, 6], k = 3 Output: trueExplanation: Possible subsets of
9 min read
Longest Possible Route in a Matrix with Hurdles
Given an M x N matrix, with a few hurdles arbitrarily placed, calculate the length of the longest possible route possible from source to a destination within the matrix. We are allowed to move to only adjacent cells which are not hurdles. The route cannot contain any diagonal moves and a location on
15+ min read
Find shortest safe route in a path with landmines
Given a path in the form of a rectangular matrix having few landmines arbitrarily placed (marked as 0), calculate length of the shortest safe route possible from any cell in the first column to any cell in the last column of the matrix. We have to avoid landmines and their four adjacent cells (left,
15+ min read
Printing all solutions in N-Queen Problem
Given an integer n, the task is to find all distinct solutions to the n-queens problem, where n queens are placed on an n * n chessboard such that no two queens can attack each other. Note: Each solution is a unique configuration of n queens, represented as a permutation of [1,2,3,....,n]. The numbe
15+ min read
Print all longest common sub-sequences in lexicographical order
You are given two strings, the task is to print all the longest common sub-sequences in lexicographical order. Examples: Input : str1 = "abcabcaa", str2 = "acbacba" Output: ababa abaca abcba acaba acaca acbaa acbcaRecommended PracticePrint all LCS sequencesTry It! This problem is an extension of lon
14 min read
Top 20 Backtracking Algorithm Interview Questions
Backtracking is a powerful algorithmic technique used to solve problems by exploring all possible solutions in a systematic and recursive manner. It is particularly useful for problems that require searching through a vast solution space, such as combinatorial problems, constraint satisfaction probl
1 min read