So this is a boring old graph problem -- return whether or not a graph has a simple path of length four. DFS plain and simple. However, unlike cycle detection or connected component determination, once you call DFS on a child, and the call returns, you need to clear the visited field for the child. Take the following ASCII art as an example:
A---B---D---E \ | \ | \| C |
Now, suppose you start a DFS from A. If the DFS starts with node B, you'll do the following:
DFS(A) with a path length of zero. DFS(B) with a path length of one. DFS(C) with a path length of two. That returns. DFS(D) with a path length of two. DFS(E) with a path length of three. That returns. DFS(D) returns that the longest path was three. DFS(B) returns that the longest path was three.At this point, we are back in DFS(A). It needs to call DFS(C) to find the path. However, if you haven't cleared out the Visited fields for B, C, D and E, you won't find the path. For that reason, when DFS(n) returns, you should clear the Visited field for n.
You also need to cut the DFS short as soon as you find the path of length four. Otherwise, your program can have an exponential blow-up of DFS calls.
Just to help you a little more -- my DFS call had two parameters: DFS(n,l). The node is n, and the path length to n is l. That lets you cut the DFS short when l reaches 4.