Uber interview question

A classic dfs problem. clear code and logic is expected