Ninja is trying to create a robot, which would talk to humans. Ninja is stuck at a particular phase where he wants the robot to create all possible sentences from a 2D array of words. Help Ninja in solving this problem. For a given 2D array of words, your task is to create all possible sentences that can be made using them.
Note :In a particular sentence, the robot can use a single word from the row that the word is part of.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
Then the T test cases follow.
The first line of each test case contains two integers ‘N’ and ‘M’ , the rows and columns of the 2D array that contains the list of words.
The next ‘N’ lines contain ‘M’ strings each.
Output format:
For each test case, all the possible sentences formed are printed in a separate line.
The output of each test case is printed in a separate line.
Note:
The output format is predefined for this question. You need to store all possibly created sentences in a predefined data structure. Keep in mind that first you need to store all the sentences that start with the first word of the first row and so on.
For further clarification on the same see the below example:
1
2 2
you we
sleep drink
In this case there are more than one correct ways to store the sentences but order of the output matters so, you should keep in mind that you start with the first row and the first column and so on.
Correct Output:
you sleep
you drink
we sleep
we drink
Incorrect outputs:
we sleep we drink you drink
we drink we sleep you sleep
you sleep you drink we drink
you drink you sleep we sleep
1 <= T <= 5
1 <= N <= 5
1 <= M <= 5
1 <= W <=20
where ‘T’ is the number of test cases, ‘N’ and ‘M’ are the dimensions of the words array, ‘array[i][j]’ is the value of words of the array, and ‘W’ denotes the size of the word.
1
2 2
you we
sleep drink
you sleep
you drink
we sleep
we drink
Taking a word from each row and adding it to each word of rest all the columns.
2
3 1
i
love
coding
3 2
you we
have are
eat read
i love coding
you have eat
you have read
you are eat
you are read
we have eat
we have read
we are eat
we are read
Think about using recursion
We will use the basic idea of depth-first traversal in order to solve this problem. We create an output array to store the created sentence. We now start by considering all the words of the first row as the starting points for sentences and store them in the output array.
Let us look at the below example:
Arr = you we
have are
sleep read
Steps:
Algorithm:
O(M^N), where N and M are the dimensions of the 2d array.
The algorithm will generate all possible sentences which will be M^N. So the overall time complexity will be O(M^N).
O((M^N) * W), where ‘N’ and ‘W’ are the number of rows in the given array and the word size, respectively.
Since we are using an array to store the sentences, the overall space complexity will be O((M^N) * W).