I could not understand the code, can you please explain how to write dfs function

Please provide the clean code with comments and time complexity for easy to understand.