Label the points:
a b c
d e f
g h i
So line 1 connects (a-d), line 2 connects (d-e) and so on. As you add lines, keep lists of connected points. So after you have added line 4, the lists are {a,d,e} and {g,h,i}. Line 5 connects (e-h), so it merges the lists into {a,d,e,g,h,i}. Then line 6 connects (d-g), two points that are already in one list, so it must form a closed loop.