Here is the standard recursive DFS template you will use constantly:
visited = [false] * (n + 1)
adj = adjacency list of the graph
function dfs(u):
visited[u] = true
// process u here
for each v in adj[u]:
if not visited[v]:
dfs(v)
// in main:
// build adj from input
// call dfs(start_vertex)
Declare a global visited array. Write a function dfs that takes a vertex . Inside: mark visited, process , loop through neighbors of , and recurse on unvisited neighbors.
This template works for nearly every DFS problem. You will modify what happens when you process a vertex, but the structure stays the same.