Some minor adjustments
A sparse matrix version of the algorithm

The sparse matrix version sacrifices some CPU cycles in return for a
massive reduction in memory usage. The required memory is reduced from
O(N²) to about O(N).