Amazon interview question

Medium difficulty coding Q about connected components.