Minimize steps required to move all 1 's in a matrix to a given index | Function to calculate and return the minimum number of steps required to move all 1 s to ( X , Y ) ; Iterate the given matrix ; Update the answer with minimum moves required for the given element to reach the given index ; Return the number of steps ; Given matrix ; Given position ; Function Call
function findAns ( mat , x , y , n , m ) { let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < m ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) { ans += Math . abs ( x - i ) + Math . abs ( y - j ) ; } } } return ans ; } let mat = [ [ 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 1 ] ] ; let x = 0 , y = 2 ; document . write ( findAns ( mat , x , y , mat . length , mat [ 0 ] . length ) + " " ) ;