Minimize count of adjacent row swaps to convert given Matrix to a Lower Triangular Matrix | Function to count the minimum number of adjacent swaps ; Stores the size of the given matrix ; Stores the count of zero at the end of each row ; Traverse the given matrix ; Count of 0 s at the end of the ith row ; Stores the count of swaps ; Traverse the cntZero array ; If count of zero in the i - th row < ( N - i - 1 ) ; Stores the index of the row where count of zero > ( N - i - 1 ) ; If no row found that satisfy the condition ; Swap the adjacent row ; Driver Code
function minAdjSwaps ( mat ) { var N = mat . length ; var cntZero = Array ( N ) . fill ( 0 ) ; for ( i = 0 ; i < N ; i ++ ) { for ( j = N - 1 ; j >= 0 && mat [ i ] [ j ] == 0 ; j -- ) { cntZero [ i ] ++ ; } } var cntSwaps = 0 ; for ( i = 0 ; i < N ; i ++ ) { if ( cntZero [ i ] < ( N - i - 1 ) ) { var First = i ; while ( First < N && cntZero [ First ] < ( N - i - 1 ) ) { First ++ ; } if ( First == N ) { return - 1 ; } while ( First > i ) { cntZero = swap ( cntZero , First , First - 1 ) ; First -- ; cntSwaps ++ ; } } } return cntSwaps ; } function swap ( arr , i , j ) { var temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } var mat = [ [ 0 , 0 , 2 ] , [ 3 , 1 , 0 ] , [ 4 , 0 , 0 ] ] ; document . write ( minAdjSwaps ( mat ) ) ;