Pregunta de entrevista de Apple

Graph traversal question with optimization follow up