Algorithm to generate dendograms for a given matrix