Google interview question

Solve DFS LeetCode question (middle)