Partial matrix (minimum movement)

i’m going to sort a following matrix :

the matrix contains sum characters for example 5 of a , 2 of b , 7 of c and so on
we want to move characters near each other with minimum movements using Dynamic Algorithms .
characters can move only in two ways : up-down / left-right .

as an example sorting the N*N matrix .

my problem is about dynamic solution and storing table …
what should i store in first steps and use it in next movements ???