Minimum cost to sort a matrix of numbers from 0 to n ^ 2 | implementation to find the total energy required to rearrange the numbers ; function to find the total energy required to rearrange the numbers ; nested loops to access the elements of the given matrix ; store quotient ; final destination location ( i_des , j_des ) of the element mat [ i ] [ j ] is being calculated ; energy required for the movement of the element mat [ i ] [ j ] is calculated and then accumulated in the 'tot_energy   ; required total energy ; Driver Program
n = 4 NEW_LINE def calculateEnergy ( mat , n ) : NEW_LINE INDENT tot_energy = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT q = mat [ i ] [ j ] // n NEW_LINE i_des = q NEW_LINE j_des = mat [ i ] [ j ] - ( n * q ) NEW_LINE tot_energy += ( abs ( i_des - i ) + abs ( j_des - j ) ) NEW_LINE DEDENT DEDENT return tot_energy NEW_LINE DEDENT mat = [ [ 4 , 7 , 0 , 3 ] , [ 8 , 5 , 6 , 1 ] , [ 9 , 11 , 10 , 2 ] , [ 15 , 13 , 14 , 12 ] ] NEW_LINE print ( " Total ▁ energy ▁ required ▁ = ▁ " , calculateEnergy ( mat , n ) , " units " ) NEW_LINE