Hint 1
First try to understand the problem carefully and then take some example and solve it on a paper.
Hint 2
Can you interpret the given input as a graph? Which graph traversal technique is suitable here?
Hint 3
Can we use some space to avoid redundant function calls?