Count all possible Paths between two Vertices
Last Updated :
25 May, 2025
Given a Directed Graph with n vertices represented as a list of directed edges represented by a 2D array edgeList[][], where each edge is defined as (u, v) meaning there is a directed edge from u to v. Additionally, you are given two vertices: source and destination.
The task is to determine the total number of distinct simple paths (i.e., paths that do not contain any cycles) from the source vertex to the destination vertex.
Note: Only acyclic (simple) paths are considered. Paths containing cycles are excluded, as they can lead to an infinite number of paths.
Examples:

Input: n = 5, edgeList[][] = [[A, B], [A, C], [A, E], [B, E], [B, D], [C, E], [D, C]], source = A, destination = D
Output: 4
Explanation: The 4 paths between A and E are:
A -> E
A -> B -> E
A -> C -> E
A -> B -> D -> C -> E
Input: n = 5, edgeList[][] = [[A, B], [A, C], [A, E], [B, E], [B, D], [C, E], [D, C]], source = A, destination = C
Output: 2
Explanation: The 2 paths between A and C are:
A -> C
A -> B -> D -> C
[Approach - 1] Using Depth-First Search - O(2^n) Time and O(n) Space
The idea is to count all unique paths from a given source to a destination in a directed graph using Depth First Search (DFS). The thought process is to recursively explore all possible paths by visiting unvisited neighbors and backtrack to try alternative routes. We observe that since the graph is directed, we only follow edges in their specified direction, and we use a visited array to avoid revisiting nodes in the current path. The approach ensures that each valid path to the destination is counted exactly once by incrementing the count only when the base case node == dest is met.
Depth-First Search for the above graph can be shown like this:
Note: The red color vertex is the source vertex and the light-blue color vertex is destination, rest are either intermediate or discarded paths.

This give four paths between source(A) and destination(E) vertex
Why this approach will not work for a graph which contains cycles?
The Problem Associated with this is that now if one more edge is added between C and B, it would make a cycle (B -> D -> C -> B). And hence after every cycle through the loop, the length path will increase and that will be considered a different path, and there would be infinitely many paths because of the cycle

Steps to implement the above idea:
- Start by building an adjacency list to represent the directed connections between nodes.
- Prepare a boolean array to keep track of which nodes have already been visited in the current path.
- Define a recursive function that explores all outgoing paths from the current node toward the target node.
- If the current node matches the destination node, increment the total and return immediately.
- For each connected node that hasn't been visited, recursively explore it as the next step in the path.
- After returning from a recursive call, unmark the node to allow its reuse in other possible paths.
- Invoke the recursive traversal from the source node and return the final count of all valid paths.
C++
// C++ Code to find count of paths between
// two vertices of a directed graph using DFS
#include <bits/stdc++.h>
using namespace std;
void dfs(int node, int dest, vector<vector<int>> &graph,
vector<bool> &visited, int &count) {
// If destination is reached,
// increment count
if (node == dest) {
count++;
return;
}
// Mark current node as visited
visited[node] = true;
// Explore all unvisited neighbors
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, dest, graph, visited, count);
}
}
// Backtrack: unmark the node
// before returning
visited[node] = false;
}
int countPaths(int n, vector<vector<int>> &edgeList,
int source, int destination) {
// Create adjacency list(1 - based indexing)
vector<vector<int>> graph(n + 1);
for (auto &edge : edgeList) {
int u = edge[0];
int v = edge[1];
graph[u].push_back(v);
}
// Track visited nodes
vector<bool> visited(n + 1, false);
int count = 0;
// Start DFS from source
dfs(source, destination, graph, visited, count);
return count;
}
int main() {
int n = 5;
// Edge list: [u, v] represents u -> v
vector<vector<int>> edgeList = {
{1, 2}, {1, 3}, {1, 5},
{2, 5}, {2, 4}, {3, 5}, {4, 3}
};
int source = 1;
int destination = 5;
cout << countPaths(n, edgeList, source, destination);
return 0;
}
Java
// Java Code to find count of paths between
// two vertices of a directed graph using DFS
import java.util.*;
class GfG {
static void dfs(int node, int dest, List<List<Integer>> graph,
boolean[] visited, int[] count) {
// If destination is reached,
// increment count
if (node == dest) {
count[0]++;
return;
}
// Mark current node as visited
visited[node] = true;
// Explore all unvisited neighbors
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
dfs(neighbor, dest, graph, visited, count);
}
}
// Backtrack: unmark the node
// before returning
visited[node] = false;
}
static int countPaths(int n, int[][] edgeList,
int source, int destination) {
// Create adjacency list(1 - based indexing)
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edgeList) {
int u = edge[0];
int v = edge[1];
graph.get(u).add(v);
}
// Track visited nodes
boolean[] visited = new boolean[n + 1];
int[] count = new int[1];
// Start DFS from source
dfs(source, destination, graph, visited, count);
return count[0];
}
public static void main(String[] args) {
int n = 5;
// Edge list: [u, v] represents u -> v
int[][] edgeList = {
{1, 2}, {1, 3}, {1, 5},
{2, 5}, {2, 4}, {3, 5}, {4, 3}
};
int source = 1;
int destination = 5;
System.out.println(countPaths(n, edgeList, source, destination));
}
}
Python
# Python Code to find count of paths between
# two vertices of a directed graph using DFS
def dfs(node, dest, graph, visited, count):
# If destination is reached,
# increment count
if node == dest:
count[0] += 1
return
# Mark current node as visited
visited[node] = True
# Explore all unvisited neighbors
for neighbor in graph[node]:
if not visited[neighbor]:
dfs(neighbor, dest, graph, visited, count)
# Backtrack: unmark the node
# before returning
visited[node] = False
def countPaths(n, edgeList, source, destination):
# Create adjacency list(1 - based indexing)
graph = [[] for _ in range(n + 1)]
for u, v in edgeList:
graph[u].append(v)
# Track visited nodes
visited = [False] * (n + 1)
count = [0]
# Start DFS from source
dfs(source, destination, graph, visited, count)
return count[0]
if __name__ == "__main__":
n = 5
# Edge list: [u, v] represents u -> v
edgeList = [
[1, 2], [1, 3], [1, 5],
[2, 5], [2, 4], [3, 5], [4, 3]
]
source = 1
destination = 5
print(countPaths(n, edgeList, source, destination))
C#
// C# Code to find count of paths between
// two vertices of a directed graph using DFS
using System;
using System.Collections.Generic;
class GfG {
static void dfs(int node, int dest, List<List<int>> graph,
bool[] visited, ref int count) {
// If destination is reached,
// increment count
if (node == dest) {
count++;
return;
}
// Mark current node as visited
visited[node] = true;
// Explore all unvisited neighbors
foreach (int neighbor in graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, dest, graph, visited, ref count);
}
}
// Backtrack: unmark the node
// before returning
visited[node] = false;
}
static int countPaths(int n, int[][] edgeList,
int source, int destination) {
// Create adjacency list(1 - based indexing)
List<List<int>> graph = new List<List<int>>();
for (int i = 0; i <= n; i++) {
graph.Add(new List<int>());
}
foreach (int[] edge in edgeList) {
int u = edge[0];
int v = edge[1];
graph[u].Add(v);
}
// Track visited nodes
bool[] visited = new bool[n + 1];
int count = 0;
// Start DFS from source
dfs(source, destination, graph, visited, ref count);
return count;
}
static void Main() {
int n = 5;
// Edge list: [u, v] represents u -> v
int[][] edgeList = {
new int[]{1, 2}, new int[]{1, 3}, new int[]{1, 5},
new int[]{2, 5}, new int[]{2, 4}, new int[]{3, 5}, new int[]{4, 3}
};
int source = 1;
int destination = 5;
Console.WriteLine(countPaths(n, edgeList, source, destination));
}
}
JavaScript
// JavaScript Code to find count of paths between
// two vertices of a directed graph using DFS
function dfs(node, dest, graph, visited, count) {
// If destination is reached,
// increment count
if (node === dest) {
count.value++;
return;
}
// Mark current node as visited
visited[node] = true;
// Explore all unvisited neighbors
for (let neighbor of graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, dest, graph, visited, count);
}
}
// Backtrack: unmark the node
// before returning
visited[node] = false;
}
function countPaths(n, edgeList, source, destination) {
// Create adjacency list(1 - based indexing)
let graph = Array.from({ length: n + 1 }, () => []);
for (let [u, v] of edgeList) {
graph[u].push(v);
}
// Track visited nodes
let visited = Array(n + 1).fill(false);
let count = { value: 0 };
// Start DFS from source
dfs(source, destination, graph, visited, count);
return count.value;
}
// Driver Code
let n = 5;
// Edge list: [u, v] represents u -> v
let edgeList = [
[1, 2], [1, 3], [1, 5],
[2, 5], [2, 4], [3, 5], [4, 3]
];
let source = 1;
let destination = 5;
console.log(countPaths(n, edgeList, source, destination));
Time Complexity: O(2^n), In the worst case, every node branches to all others, exploring all simple paths.
Space Complexity: O(n), Stack space for recursion and visited array proportional to number of nodes.
[Approach - 2] Using Topological Sort - O(n) Time and O(n) Space
The idea is to count all paths from a source to destination in a directed graph using topological sorting. The thought process is that by processing nodes in topological order, we ensure we always compute paths after all its predecessors are processed. We maintain a ways[] array where ways[i] stores the number of paths to reach node i from the source. An important observation is that once we know the number of ways to reach a node, we can propagate that to its outgoing neighbors.
Steps to implement the above idea:
- Construct the adjacency list from the given edge list using 1-based indexing for all graph nodes.
- Initialize an indegree array to count incoming edges for each node for topological sorting.
- Use queue to generate the topological order of the graph.
- Create a ways array to store the number of distinct paths to each node from the source.
- Set the path count of the source node to 1 as a base for path propagation.
- Traverse all nodes in topological order and for each node update its neighbors' path counts.
- Return the value at the destination node from the ways array as the total number of paths.
C++
// C++ Code to count paths from source
// to destinattion using Topological Sort
#include <bits/stdc++.h>
using namespace std;
int countPaths(int n, vector<vector<int>> &edgeList,
int source, int destination) {
// Create adjacency list (1-based indexing)
vector<vector<int>> graph(n + 1);
vector<int> indegree(n + 1, 0);
for (auto &edge : edgeList) {
int u = edge[0];
int v = edge[1];
graph[u].push_back(v);
indegree[v]++;
}
// Perform topological sort using Kahn's algorithm
queue<int> q;
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
vector<int> topoOrder;
while (!q.empty()) {
int node = q.front();
q.pop();
topoOrder.push_back(node);
for (int neighbor : graph[node]) {
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
q.push(neighbor);
}
}
}
// Array to store number of ways to reach each node
vector<int> ways(n + 1, 0);
ways[source] = 1;
// Traverse in topological order
for (int node : topoOrder) {
for (int neighbor : graph[node]) {
ways[neighbor] += ways[node];
}
}
return ways[destination];
}
int main() {
int n = 5;
// Edge list: [u, v] represents u -> v
vector<vector<int>> edgeList = {
{1, 2}, {1, 3}, {1, 5},
{2, 5}, {2, 4}, {3, 5}, {4, 3}
};
int source = 1;
int destination = 5;
cout << countPaths(n, edgeList, source, destination);
return 0;
}
Java
// Java Code to count paths from source
// to destinattion using Topological Sort
import java.util.*;
class GfG {
static int countPaths(int n, int[][] edgeList,
int source, int destination) {
// Create adjacency list (1-based indexing)
List<Integer>[] graph = new ArrayList[n + 1];
int[] indegree = new int[n + 1];
for (int i = 0; i <= n; i++) {
graph[i] = new ArrayList<>();
}
for (int[] edge : edgeList) {
int u = edge[0];
int v = edge[1];
graph[u].add(v);
indegree[v]++;
}
// Perform topological sort using Kahn's algorithm
Queue<Integer> q = new LinkedList<>();
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0) {
q.add(i);
}
}
List<Integer> topoOrder = new ArrayList<>();
while (!q.isEmpty()) {
int node = q.poll();
topoOrder.add(node);
for (int neighbor : graph[node]) {
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
q.add(neighbor);
}
}
}
// Array to store number of ways to reach each node
int[] ways = new int[n + 1];
ways[source] = 1;
// Traverse in topological order
for (int node : topoOrder) {
for (int neighbor : graph[node]) {
ways[neighbor] += ways[node];
}
}
return ways[destination];
}
public static void main(String[] args) {
int n = 5;
// Edge list: [u, v] represents u -> v
int[][] edgeList = {
{1, 2}, {1, 3}, {1, 5},
{2, 5}, {2, 4}, {3, 5}, {4, 3}
};
int source = 1;
int destination = 5;
System.out.println(countPaths(n, edgeList, source, destination));
}
}
Python
# Python Code to count paths from source
# to destinattion using Topological Sort
from collections import deque
def countPaths(n, edgeList, source, destination):
# Create adjacency list (1-based indexing)
graph = [[] for _ in range(n + 1)]
indegree = [0] * (n + 1)
for u, v in edgeList:
graph[u].append(v)
indegree[v] += 1
# Perform topological sort using Kahn's algorithm
q = deque()
for i in range(1, n + 1):
if indegree[i] == 0:
q.append(i)
topoOrder = []
while q:
node = q.popleft()
topoOrder.append(node)
for neighbor in graph[node]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
q.append(neighbor)
# Array to store number of ways to reach each node
ways = [0] * (n + 1)
ways[source] = 1
# Traverse in topological order
for node in topoOrder:
for neighbor in graph[node]:
ways[neighbor] += ways[node]
return ways[destination]
if __name__ == "__main__":
n = 5
# Edge list: [u, v] represents u -> v
edgeList = [
[1, 2], [1, 3], [1, 5],
[2, 5], [2, 4], [3, 5], [4, 3]
]
source = 1
destination = 5
print(countPaths(n, edgeList, source, destination))
C#
// C# Code to count paths from source
// to destinattion using Topological Sort
using System;
using System.Collections.Generic;
class GfG {
static int countPaths(int n, int[][] edgeList,
int source, int destination) {
// Create adjacency list (1-based indexing)
List<int>[] graph = new List<int>[n + 1];
int[] indegree = new int[n + 1];
for (int i = 0; i <= n; i++) {
graph[i] = new List<int>();
}
foreach (var edge in edgeList) {
int u = edge[0];
int v = edge[1];
graph[u].Add(v);
indegree[v]++;
}
// Perform topological sort using Kahn's algorithm
Queue<int> q = new Queue<int>();
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0) {
q.Enqueue(i);
}
}
List<int> topoOrder = new List<int>();
while (q.Count > 0) {
int node = q.Dequeue();
topoOrder.Add(node);
foreach (int neighbor in graph[node]) {
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
q.Enqueue(neighbor);
}
}
}
// Array to store number of ways to reach each node
int[] ways = new int[n + 1];
ways[source] = 1;
// Traverse in topological order
foreach (int node in topoOrder) {
foreach (int neighbor in graph[node]) {
ways[neighbor] += ways[node];
}
}
return ways[destination];
}
static void Main() {
int n = 5;
// Edge list: [u, v] represents u -> v
int[][] edgeList = {
new int[]{1, 2}, new int[]{1, 3}, new int[]{1, 5},
new int[]{2, 5}, new int[]{2, 4}, new int[]{3, 5}, new int[]{4, 3}
};
int source = 1;
int destination = 5;
Console.WriteLine(countPaths(n, edgeList, source, destination));
}
}
JavaScript
// JavaScript Code to count paths from source
// to destinattion using Topological Sort
function countPaths(n, edgeList, source, destination) {
// Create adjacency list (1-based indexing)
let graph = Array.from({ length: n + 1 }, () => []);
let indegree = Array(n + 1).fill(0);
for (let [u, v] of edgeList) {
graph[u].push(v);
indegree[v]++;
}
// Perform topological sort using Kahn's algorithm
let q = [];
for (let i = 1; i <= n; i++) {
if (indegree[i] === 0) {
q.push(i);
}
}
let topoOrder = [];
while (q.length > 0) {
let node = q.shift();
topoOrder.push(node);
for (let neighbor of graph[node]) {
indegree[neighbor]--;
if (indegree[neighbor] === 0) {
q.push(neighbor);
}
}
}
// Array to store number of ways to reach each node
let ways = Array(n + 1).fill(0);
ways[source] = 1;
// Traverse in topological order
for (let node of topoOrder) {
for (let neighbor of graph[node]) {
ways[neighbor] += ways[node];
}
}
return ways[destination];
}
// Driver Code
let n = 5;
// Edge list: [u, v] represents u -> v
let edgeList = [
[1, 2], [1, 3], [1, 5],
[2, 5], [2, 4], [3, 5], [4, 3]
];
let source = 1;
let destination = 5;
console.log(countPaths(n, edgeList, source, destination));
Time Complexity: O(n + e), Each node and edge is processed once for topological sort and path update, where e is the total number of edges.
Space Complexity: O(n + e), Extra space is used for the adjacency list, indegree array, and ways array.
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 conti
4 min read
Standard problems on backtracking
The Knight's tour problemGiven 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
15+ min read
Rat in a MazeGiven 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 1.
9 min read
N Queen ProblemGiven 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 BacktrackingGiven 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 ProblemGiven 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.ExamplesInput: V = 4, edges[][] = [[0, 1], [0, 2], [0,3], [1, 3], [2, 3]], m = 3Output:
13 min read
Hamiltonian CycleHamiltonian 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 a graph contains a Hamiltonian cycle, it is called Hamiltonian graph otherwise it is non-Hamiltonian.Finding a Hamiltonian Cycle in a graph is a well-known NP-complet
12 min read
Algorithm to Solve Sudoku | Sudoku SolverGiven 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 dig
15+ min read
Magnet PuzzleThe 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 ParenthesesGiven a string str consisting only of lowercase letters and the characters '(' and ')'. Your task is to delete minimum parentheses so that the resulting string is balanced, i.e., every opening parenthesis has a matching closing parenthesis in the correct order, and no extra closing parentheses appea
15+ min read
A backtracking approach to generate n bit Gray CodesGiven 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 StringGiven 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 ArrayGiven 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) t
12 min read
Check if a given string is sum-stringGiven a string s, the task is to determine whether it can be classified as a sum-string. A string is a sum-string if it can be split into more than two substring such that, the rightmost substring is equal to the sum of the two substrings immediately before it. This rule must recursively apply to th
14 min read
Count all possible Paths between two VerticesGiven a Directed Graph with n vertices represented as a list of directed edges represented by a 2D array edgeList[][], where each edge is defined as (u, v) meaning there is a directed edge from u to v. Additionally, you are given two vertices: source and destination. The task is to determine the tot
15+ min read
Find all distinct subsets of a given set using BitMasking ApproachGiven an array arr[] that may contain duplicates. The task is to return all possible subsets. Return only unique subsets and they can be in any order.Note: The individual subsets should be sorted.Examples: Input: arr[] = [1, 2, 2]Output: [], [1], [2], [1, 2], [2, 2], [1, 2, 2]Explanation: The total
7 min read
Find if there is a path of more than k weight from a sourceGiven an undirected graph represented by the edgeList[][], where each edgeList[i] contains three integers [u, v, w], representing an undirected edge from u to v, having distance w. You are also given a source vertex, and a positive integer k. Your task is to determine if there exist a simple path (w
10 min read
Print all paths from a given source to a destinationGiven 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. Th
12 min read
Print all possible strings that can be made by placing spacesGiven 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 WarGiven an array arr[] of size n, the task is to divide it into two subsets such that the absolute difference between the sum of elements in the two subsets.If n is even, both subsets must have exactly n/2 elements.If n is odd, one subset must have (nâ1)/2 elements and the other must have (n+1)/2 elem
11 min read
8 queen problemGiven an 8x8 chessboard, the task is to place 8 queens on the board such that no 2 queens threaten each other. Return a matrix of size 8x8, where 1 represents queen and 0 represents an empty position. Approach:The idea is to use backtracking to place the queens one by one on the board. Starting from
9 min read
Combination SumGiven 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 frequency
8 min read
Warnsdorff's algorithm for Knightâs tour problemProblem : 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 mazeGiven 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 swapsGiven 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 allowedYou 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 va
11 min read
N Queen in O(n) spaceGiven 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, th
7 min read
Hard problems on Backtracking
Power Set in Lexicographic orderThis 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 BacktrackingGiven 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 sumGiven 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 HurdlesGiven 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 landminesGiven 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 ProblemGiven 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 orderYou 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