helper functions to build a distance matrix