I must admit that this problem actually took me a good while to solve. Once you have the right insight on forming a magic Square it is really straight forward. But until that point I was just stuck. Anyway, before rambling on lets get to the actual problem.
We define a magic square to be an matrix of distinct positive integers from 1 to n2 where the sum of any row, column, or diagonal (of length n) is always equal to the same number (i.e., the magic constant).
Consider a matrix, s, of integers in the inclusive range [1, 9]. We can convert any digit, a, to any other digit, b, in the range [1, 9] at cost .
Given , convert it into a magic square at minimal cost by changing zero or more of its digits. Then print this cost on a new line.
Note: The resulting magic square must contain distinct integers in the inclusive range [1, 9].