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
def minAdjSwaps ( mat ) : NEW_LINE INDENT N = len ( mat ) NEW_LINE cntZero = [ 0 ] * ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if mat [ i ] [ j ] != 0 : NEW_LINE INDENT break NEW_LINE DEDENT cntZero [ i ] += 1 NEW_LINE DEDENT DEDENT cntSwaps = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( cntZero [ i ] < ( N - i - 1 ) ) : NEW_LINE INDENT First = i NEW_LINE while ( First < N and cntZero [ First ] < ( N - i - 1 ) ) : NEW_LINE INDENT First += 1 NEW_LINE DEDENT if ( First == N ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT while ( First > i ) : NEW_LINE INDENT cntZero [ First ] = cntZero [ First - 1 ] NEW_LINE cntZero [ First - 1 ] = cntZero [ First ] NEW_LINE First -= 1 NEW_LINE cntSwaps += 1 NEW_LINE DEDENT DEDENT DEDENT return cntSwaps NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 0 , 0 , 2 ] , [ 3 , 1 , 0 ] , [ 4 , 0 , 0 ] ] NEW_LINE print ( minAdjSwaps ( mat ) ) NEW_LINE DEDENT