You are given a maze consisting of N cells numbered from 0 to N - 1 and an array ‘arr’ of N integers in which arr[i] contains the cell number that can be reached from ‘i’th cell in one step. You are supposed to find the length of the largest cycle in the maze, given that each cell has less than or equal to 1 exit but can have multiple entry points.
Note:The maze may contain self-cycles.
arr[i] = -1 means the ‘i’th cell doesn’t have an exit.
The first line of input contains an integer ‘T’, denoting the number of test cases. The test cases follow.
The first line of each test case contains integer ‘N’, which denotes the number of cells in the maze.
The second line contains N integers, denoting the elements of the array ‘arr’.
Output Format:
For each test case, print the length of the largest cycle in the maze and -1 if there are no cycles.
Print the output of each test case in a separate line.
1<= T <= 50
1 <= N <= 10,000
-1 <= arr[i] <= N-1
Where ’T’ is the number of test cases, and N denotes the number of cells in the maze and arr[i] is the cell that can be reached from ‘i’th cell.
Time Limit: 1 sec
2
5
-1 2 3 4 1
10
-1 4 -1 -1 6 -1 7 8 9 1
4
6
In the first test case, there are 5 cells in the maze.
‘i’th cell - exit cell of ‘i’th cell
0 - -1
1 - 2
2 - 3
3 - 4
4 - 1
This maze consists of 1 cycle 1 -> 2 -> 3 -> 4 -> 1 (length = 4). So, the maximum length of the cycle is 4.
In the second test case, there are 10 cells in the maze.
‘i’th cell - exit cell of ‘i’th cell
0 - 2
1 - 4
2 - 0
3 - 5
4 - 6
5 - 3
6 - 7
7 - 8
8 - 9
9 - 1
This maze contains 3 cycles 0 -> 2 ->0 (length = 0), 1 -> 4 -> 6 -> 7 -> 8 ->9 -> 1 (length = 6), and 3 -> 5 -> 3 (length = 2). So, the maximum length of the cycle is 6.
2
7
-1 2 1 4 3 6 5
6
1 2 3 4 5 0
2
6
Can you apply a Depth-first search to find the largest cycle?
The idea is to do a depth-first search to find all the cycles which are formed and calculate the length of the largest cycle. We are treating the array as a graph of directed edges. Whenever we get into any of the cells in the cycle, using dfs we will visit all the subsequent cells in the cycle. Out of all the cycles, we will return the cycle of maximum length.
The steps are as follows:
O(N), where N is the number of cells in the maze.
As the time complexity of a Depth-first Search is O(V+E), where V is the number of vertices and E is the number of edges in the graph. Here the number of vertices is N, and the number of edges is at most N. Hence the overall time complexity is O(N).
O(N), where N is the number of cells in the maze.
We are using a visited array of size N and a positions array of size N. Hence, the overall space complexity is O(N).