I'd first define a 2-dimensional system to identify the terrain-data and to identify all distinct border pieces within the same terrain. You should be able of identifying all 4 borders of any terrain-piece. You should also be able of identifying the crossings in the same way.
you should have an algorithm to find its borders and border-crossings.
One possibility might be to define that every piece of terrain has it's own borders and crossings and make the identification dependant like that: