The Wayback Machine - https://web.archive.org/web/20230329214042/https://www.geeksforgeeks.org/count-of-simple-paths-starting-from-source-node/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Count of simple paths starting from source node

Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 28 Mar, 2023
Improve Article
Save Article
Like Article

Given an undirected graph with N nodes and M edges in the form of array edg[][2], the task is to count all simple paths (paths without repeated vertices) from source node 1 in the given graph.

Examples:

Input: N = 4, edg[][2] = {{1, 2}, {2, 3}}
Output: 3
Explanation:  

  • path 1: 1
  • path 2: 1 -> 2
  • path 3: 1 -> 2 -> 3

Input: N = 4, edg[][2] = {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3 4}}
Output:  16

Approach: To solve the problem follow the below idea:

The idea is to use recursion to traverse the graph starting from the source node and keep track of visited nodes and increment the counter for each path found. Traverse unvisited neighbors, and unmarks visited nodes so that multiple paths can be explored. Returns the total count of simple paths found.

Below are the steps for the above approach:

  • Declare adjacency list adj[N + 1] and iterate on all M edges and fill adjacency list.
  • Initialize a visited array of size N+1 with 0, vis[N + 1].
  • Declare a variable say ans = 0.
  • Create recursive function recur(), mark the current node visited and increment the ans by 1 and traverse its unvisited neighbors.
  • When exiting the current node, unmark the node from the visited array.
  • Return the variable ans.

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// recursive function
void recur(int v, int& ans, vector<vector<int> >& adj,
           vector<int>& vis)
{
 
    // Marking current node visited
    vis[v] = 1;
 
    // Incrementing the counter
    ans++;
 
    // Traversing for unvisited neighbors
    for (auto& u : adj[v]) {
        if (!vis[u]) {
            recur(u, ans, adj, vis);
        }
    }
 
    // Unmarking for counting all simple
    // paths
    vis[v] = 0;
}
 
// Function to count number of simple
// paths from given source node 1
int isPossible(int N, int edg[][2], int M)
{
 
    // Initializing adjacency list
    vector<vector<int> > adj(N + 1);
 
    // Filling adjacency List
    for (int i = 0; i < M; i++) {
        adj[edg[i][0]].push_back(edg[i][1]);
        adj[edg[i][1]].push_back(edg[i][0]);
    }
 
    // Visited array for recursion
    vector<int> vis(N + 1, 0);
 
    // Counter initialized to zero
    int ans = 0;
 
    // Calling dfs function
    recur(1, ans, adj, vis);
 
    // Returning answer
    return ans;
}
 
// Driver Code
int main()
{
 
    // Input 1
    int N = 4, edg[][2] = { { 1, 2 }, { 2, 3 } };
    int M = 2;
 
    // Function Call
    cout << isPossible(N, edg, M) << endl;
 
    return 0;
}

Java




// java code to implement the approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // recursive function
    static void recur(int v, int[] ans,
                      ArrayList<ArrayList<Integer> > adj,
                      int[] vis)
    {
 
        // Marking current node visited
        vis[v] = 1;
 
        // Incrementing the counter
        ans[0]++;
 
        // Traversing for unvisited neighbors
        for (int u : adj.get(v)) {
            if (vis[u] == 0) {
                recur(u, ans, adj, vis);
            }
        }
 
        // Unmarking for counting all simple paths
        vis[v] = 0;
    }
 
    // Function to count number of simple paths from given
    // source node 1
    static int isPossible(int N, int[][] edg, int M)
    {
 
        // Initializing adjacency list
        ArrayList<ArrayList<Integer> > adj
            = new ArrayList<>();
        for (int i = 0; i <= N; i++) {
            adj.add(new ArrayList<Integer>());
        }
 
        // Filling adjacency List
        for (int i = 0; i < M; i++) {
            adj.get(edg[i][0]).add(edg[i][1]);
            adj.get(edg[i][1]).add(edg[i][0]);
        }
 
        // Visited array for recursion
        int[] vis = new int[N + 1];
 
        // Counter initialized to zero
        int[] ans = { 0 };
 
        // Calling dfs function
        recur(1, ans, adj, vis);
 
        // Returning answer
        return ans[0];
    }
 
    public static void main(String[] args)
    {
        // Input 1
        int N = 4;
        int[][] edg = { { 1, 2 }, { 2, 3 } };
        int M = 2;
 
        // Function Call
        System.out.println(isPossible(N, edg, M));
    }
}
 
// This code is contributed by lokesh.

Output

3

Time Complexity: O(N!)  
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!