To prevent infinite loops in graphs with cycles, you track which vertices you have already visited. Use a boolean array: visited[u] = true means you have been to vertex . Before recursing to a neighbor, check if it is already visited.
If yes, skip it. If no, mark it visited and recurse. This simple mechanism prevents your DFS from looping forever. Without it, a graph like would cause infinite recursion: visit , go to , go back to , go to , forever.