Machine Learning partitioning algorithm, with a two-dimensional version and an n-dimensional version with memoization