Expansion algorithm for the density matrix