Creating connected graph algorithm