Find minimum moves to bring all elements in one cell of a matrix | Javascript implementation to find the minimum number of moves to bring all non - zero element in one cell of the matrix ; Function to find the minimum number of moves to bring all elements in one cell of matrix ; Moves variable to store the sum of number of moves ; Loop to count the number of the moves ; Condition to check that the current cell is a non - zero element ; Coordinates of given cell ; Given Matrix ; Element to be moved ; Function call
let M = 4 ; let N = 5 ; function no_of_moves ( Matrix , x , y ) { let moves = 0 ; for ( let i = 0 ; i < M ; i ++ ) { for ( let j = 0 ; j < N ; j ++ ) { if ( Matrix [ i ] [ j ] != 0 ) { moves += Math . abs ( x - i ) ; moves += Math . abs ( y - j ) ; } } } document . write ( moves ) ; } let x = 3 ; let y = 2 ; let Matrix = [ [ 1 , 0 , 1 , 1 , 0 ] , [ 0 , 1 , 1 , 0 , 1 ] , [ 0 , 0 , 1 , 1 , 0 ] , [ 1 , 1 , 1 , 0 , 0 ] ] ; let num = 1 ; no_of_moves ( Matrix , x , y ) ;