
A way to reach city 1 from city 3 can be: 32421
Here we revisited city 2 to reach city 1.
A way to reach city 3 from city 1 can be: 12423
Here we revisited city 2 to reach city 3.
Orders 32421 and 12423 are to be considered different.
The first line of input contains an integer ‘T’, the number of test cases.
The first line of each test case contains two single space-separated integers, ‘N’ and ‘M’, representing the number of cities and the number of roads, respectively.
The next ‘M’ lines will denote the road between city ‘X’ and city ‘Y’ defined by two single space-separated integers ‘X' and 'Y'.
For each test case, print the number of ways in which cities can be visited modulo 1000000007.
Print the output of each test case in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10
N - 1 <= M <= N*(N - 1) / 2
1 <= X, Y <= N and X != Y
Time Limit : 1 sec
The basic idea is to generate all permutations in which cities can be visited. For each permutation, we create a map to store the adjacent cities. If a city is not present in the map then the path will not be valid, else valid.
Example:
Let a permutation be: 1 3 2 4
We create a map and insert the first element of permutation initially into it. Map : {1}
We now add all adjacent cities of 1 into the map, so the map becomes: {1, 2, 3, 4}
We move to the next element in the permutation, i.e., 3 which is present in the map and add its adjacent cities into the map.
As all the cities are present in the map, so the permutation will be valid.
Now, let a permutation be: 1 4 3 2
Similarly, we will create a map and insert 1 into the map, so the map biomes: {1}
We will insert cities adjacent to 1 into the map, so the map now becomes: {1, 2, 3}
We move to the next element in the permutation, i.e., 4 which is not present in the map.
The permutation becomes invalid as 4 was not present in the map.
We can do this for all the permutations to count the number of valid ways.
Here is the algorithm :
HELPER(‘GRAPH’, ‘ARR’, ‘SI’, ‘EI, ‘RES’)
CALC(‘GRAPH’, ‘ARR’, ‘N’)
Approach: In this approach, we will try to optimize the brute force approach with the help of DP with Bitmasking.
Bitmasking: If we want to represent a subset of a set with N elements, this subset can be encoded by a sequence of N bits. This sequence is called a bitmask. The basic idea is to use a bitmask where i-th bit will represent whether the i-th element has been included or not.
We will define DP[{MASK1, MASK2}], where MASK1 is a subset of total cities from where we can start the travel and MASK2 represents the cities available to visit. So, DP[MASK1][MASK2] will present the number of ways starting from cities in MASK1 we can travel the cities in MASK2.
As there are total ‘N ‘cities, MASK1 and MASK2 will be of N bits.
Algorithm:
6. Finally, return ans.
GET(‘G’, ‘M1’, ‘M2’, ‘DP’)