Suppose you have an N x N matrix of element type T.
Let's say the eight neighbours of a given element E are the other cells in the 3x3 square with E at its center:
.......
.......
...XXX.
...XEX.
...XXX.
.......
X = neighbour
There is a commutative binary function f(a,b) on pairs of T that returns a float between 0.0 and 1.0.  (f(a,b) = f(b,a) and f(a,a) = 0 for all a, b in T.)
We want to rearrange the elements of the matrix to minimize the total of f between neighbouring cells.
That is, we want to minimize totalf:
totalf = 0
for x in 1 to N
  for y in 1 to N
    for dx in -1 to +1
      for dy in -1 to +1
        totalf += f(M[x,y], M[x+dx,y+dy])
Any ideas? Is there a standard problem this is similar to?