Minimum cost to sort a matrix of numbers from 0 to n ^ 2 | 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 Code
< ? php function calculateEnergy ( $ mat , $ n ) { $ i_des ; $ j_des ; $ q ; $ tot_energy = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { $ q = ( int ) ( $ mat [ $ i ] [ $ j ] / $ n ) ; $ i_des = $ q ; $ j_des = $ mat [ $ i ] [ $ j ] - ( $ n * $ q ) ; $ tot_energy += abs ( $ i_des - $ i ) + abs ( $ j_des - $ j ) ; } } return $ tot_energy ; } $ mat = array ( array ( 4 , 7 , 0 , 3 ) , array ( 8 , 5 , 6 , 1 ) , array ( 9 , 11 , 10 , 2 ) , array ( 15 , 13 , 14 , 12 ) ) ; $ n = 4 ; echo " Total ▁ energy ▁ required ▁ = ▁ " , calculateEnergy ( $ mat , $ n ) , " ▁ units " ; ? >