Amazon interview question

DFS question from leetcode