text: Print all elements in sorted order from row and column wise sorted matrix | Python 3 program to Print all elements in sorted order from row and column wise sorted matrix ; A utility function to youngify a Young Tableau . This is different from standard youngify . It assumes that the value at mat [ 0 ] [ 0 ] is infinite . ; Find the values at down and right sides of mat [ i ] [ j ] ; If mat [ i ] [ j ] is the down right corner element , return ; Move the smaller of two values ( downVal and rightVal ) to mat [ i ] [ j ] and recur for smaller value ; A utility function to extract minimum element from Young tableau ; This function uses extractMin ( ) to print elements in sorted order ; Driver Code
code: import sys NEW_LINE INF = sys . maxsize NEW_LINE N = 4 NEW_LINE def youngify ( mat , i , j ) : NEW_LINE INDENT downVal = mat [ i + 1 ] [ j ] if ( i + 1 < N ) else INF NEW_LINE rightVal = mat [ i ] [ j + 1 ] if ( j + 1 < N ) else INF NEW_LINE if ( downVal == INF and rightVal == INF ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( downVal < rightVal ) : NEW_LINE INDENT mat [ i ] [ j ] = downVal NEW_LINE mat [ i + 1 ] [ j ] = INF NEW_LINE youngify ( mat , i + 1 , j ) NEW_LINE DEDENT else : NEW_LINE INDENT mat [ i ] [ j ] = rightVal NEW_LINE mat [ i ] [ j + 1 ] = INF NEW_LINE youngify ( mat , i , j + 1 ) NEW_LINE DEDENT DEDENT def extractMin ( mat ) : NEW_LINE INDENT ret = mat [ 0 ] [ 0 ] NEW_LINE mat [ 0 ] [ 0 ] = INF NEW_LINE youngify ( mat , 0 , 0 ) NEW_LINE return ret NEW_LINE DEDENT def printSorted ( mat ) : NEW_LINE INDENT print ( " Elements ▁ of ▁ matrix ▁ in ▁ sorted ▁ order ▁ n " ) NEW_LINE i = 0 NEW_LINE while i < N * N : NEW_LINE INDENT print ( extractMin ( mat ) , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 10 , 20 , 30 , 40 ] , [ 15 , 25 , 35 , 45 ] , [ 27 , 29 , 37 , 48 ] , [ 32 , 33 , 39 , 50 ] ] NEW_LINE printSorted ( mat ) NEW_LINE DEDENT