Correctly handle connected components