Recursively print all sentences that can be formed from list of word lists

27 Jun, 2022
Given a list of word lists How to print all sentences possible taking one word from a list at a time via recursion? 
Example: 
Input: {{"you", "we"},
        {"have", "are"},
        {"sleep", "eat", "drink"}}

Output:
  you have sleep
  you have eat
  you have drink
  you are sleep
  you are eat
  you are drink
  we have sleep
  we have eat
  we have drink
  we are sleep
  we are eat
  we are drink 
We strongly recommend minimizing your browser and try this yourself first. The idea is based on a simple depth-first traversal. We start from every word of the first list as the first word of an output sentence, then recur for the remaining lists.
Below is the C++ implementation of the above idea. In the below implementation, the input list of the list is considered as a 2D array. If we take a closer look, we can observe that the code is very close to the DFS of graph.
C++
Java
Python3
C#
Javascript
// C++ program to print all possible sentences from a list of word list#include <iostream>#include <string> #define R 3#define C 3using namespace std; // A recursive function to print all possible sentences that can be formed// from a list of word listvoid printUtil(string arr[R][C], int m, int n, string output[R]){    // Add current word to output array    output[m] = arr[m][n];     // If this is last word of current output sentence, then print    // the output sentence    if (m==R-1)    {        for (int i=0; i<R; i++)           cout << output[i] << " ";        cout << endl;        return;    }     // Recur for next row    for (int i=0; i<C; i++)       if (arr[m+1][i] != "")          printUtil(arr, m+1, i, output);} // A wrapper over printUtil()void print(string arr[R][C]){   // Create an array to store sentence   string output[R];    // Consider all words for first row as starting points and   // print all sentences   for (int i=0; i<C; i++)     if (arr[0][i] != "")        printUtil(arr, 0, i, output);} // Driver program to test above functionsint main(){   string arr[R][C]  = {{"you", "we"},                        {"have", "are"},                        {"sleep", "eat", "drink"}};    print(arr);    return 0;}
// Java program to print// all possible sentences// from a list of word listclass GFG{ static final int R= 3;static final int C =3;   // A recursive function to// print all possible sentences// that can be formed // from a list of word liststatic void printUtil(String [][]arr,                      int m, int n,                      String []output){  // Add current word to output array  output[m] = arr[m][n];   // If this is last word of  // current output sentence,  // then print the output sentence  if (m == R - 1)  {    for (int i = 0; i < R; i++)      System.out.print(output[i] + " ");    System.out.println();    return;  }   // Recur for next row  for (int i = 0; i < C; i++)    if (arr[m + 1][i] != "" && m < C)      printUtil(arr, m + 1, i, output);} // A wrapper over printUtil()static void print(String [][]arr){  // Create an array to store sentence  String []output = new String[R];   // Consider all words for first  // row as starting points and  // print all sentences  for (int i = 0; i < C; i++)    if (arr[0][i] != "")      printUtil(arr, 0, i, output);} // Driver program to test above functionspublic static void main(String[] args){  String [][]arr  = {{"you", "we", ""},                     {"have", "are", ""},                     {"sleep", "eat", "drink"}};  print(arr);}} // This code is contributed by gauravrajput1
# Python program recursively print all sentences that can be# formed from list of word listsR = 3C = 3 # A recursive function to print all possible sentences that can# be formed from a list of word listdef printUtil(arr, m, n, output):     # Add current word to output array    output[m] = arr[m][n]     # If this is last word of current output sentence, then print    # the output sentence    if m==R-1:        for i in range(R):            print (output[i],end= " ")        print()        return     # Recur for next row    for i in range(C):        if arr[m+1][i] != "":            printUtil(arr, m+1, i, output) # A wrapper over printUtildef printf(arr):     # Create an array to store sentence    output = [""] * R     # Consider all words for first row as starting    #  points and print all sentences    for i in range(C):        if arr[0][i] != "":            printUtil(arr, 0, i, output) # Driver programarr = [ ["you", "we",""],        ["have", "are",""],        ["sleep", "eat", "drink"]]printf(arr)# This code is contributed by Bhavya Jain
// C# program to print// all possible sentences// from a list of word listusing System;class GFG{ static readonly int R= 3;static readonly int C =3;   // A recursive function to// print all possible sentences// that can be formed // from a list of word liststatic void printUtil(String [,]arr,                      int m, int n,                      String []output){  // Add current word to output array  output[m] = arr[m, n];   // If this is last word of  // current output sentence,  // then print the output sentence  if (m == R - 1)  {    for (int i = 0; i < R; i++)      Console.Write(output[i] + " ");    Console.WriteLine();    return;  }   // Recur for next row  for (int i = 0; i < C; i++)    if (arr[m + 1, i] != "" && m < C)      printUtil(arr, m + 1, i, output);} // A wrapper over printUtil()static void print(String [,]arr){  // Create an array to store sentence  String []output = new String[R];   // Consider all words for first  // row as starting points and  // print all sentences  for (int i = 0; i < C; i++)    if (arr[0, i] != "")      printUtil(arr, 0, i, output);} // Driver program to test above functionspublic static void Main(String[] args){  String [,]arr  = {{"you", "we", ""},                    {"have", "are", ""},                    {"sleep", "eat", "drink"}};  print(arr);}} // This code is contributed by gauravrajput1
<script> // JavaScript program recursively print all sentences that can be// formed from list of word listsconst R = 3const C = 3 // A recursive function to print all possible sentences that can// be formed from a list of word listfunction printUtil(arr, m, n, output){     // Add current word to output array    output[m] = arr[m][n]     // If this is last word of current output sentence, then print    // the output sentence    if(m == R - 1){        for(let i = 0; i < R; i++)            document.write(output[i]," ")        document.write("</br>")        return    }     // Recur for next row    for(let i = 0; i < C; i++){        if(arr[m+1][i] != "")            printUtil(arr, m+1, i, output)    }} // A wrapper over printUtilfunction printf(arr){     // Create an array to store sentence    let output = new Array(R).fill("")     // Consider all words for first row as starting    //  points and print all sentences    for(let i = 0; i < C; i++){        if(arr[0][i] != "")            printUtil(arr, 0, i, output)    }} // Driver programlet arr = [ ["you", "we",""],        ["have", "are",""],        ["sleep", "eat", "drink"]]printf(arr) // This code is contributed by shinjanpatra </script>
you have sleep 
you have eat 
you have drink 
you are sleep 
you are eat 
you are drink 
we have sleep 
we have eat 
we have drink 
we are sleep 
we are eat 
we are drink 

GauravRajput1
amartyaghoshgfg
shinjanpatra
hardikkoriintern
DFS
Strings
Strings
DFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Data Structure: Types, Classifications and Applications
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
Print all subsequences of a string
A Program to check if strings are rotations of each other or not
String class in Java | Set 1
Palindrome Partitioning | DP-17
Find the smallest window in a string containing all characters of another string
Convert character array to string in C++
Remove first and last character of a string in Java