Modify a given matrix by placing sorted boundary elements in clockwise manner | Function to print the elements of the matrix in row - wise manner ; Function to sort boundary elements of a matrix starting from the outermost to the innermost boundary and place them in a clockwise manner ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Stores the current boundary elements ; Push the first row ; Push the last column ; Push the last row ; Push the first column ; Sort the boundary elements ; Update the first row ; Update the last column ; Update the last row ; Update the first column ; Print the resultant matrix ; Driver Code ; Given matrix
def printMatrix ( a ) : NEW_LINE INDENT for x in a : NEW_LINE INDENT for y in x : NEW_LINE INDENT print ( y , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def sortBoundaryWise ( a ) : NEW_LINE INDENT k = 0 NEW_LINE l = 0 NEW_LINE m = len ( a ) NEW_LINE n = len ( a [ 0 ] ) NEW_LINE n_k = 0 NEW_LINE n_l = 0 NEW_LINE n_m = m NEW_LINE n_n = n NEW_LINE while ( k < m and l < n ) : NEW_LINE INDENT boundary = [ ] NEW_LINE for i in range ( l , n ) : NEW_LINE INDENT boundary . append ( a [ k ] [ i ] ) NEW_LINE DEDENT k += 1 NEW_LINE for i in range ( k , m ) : NEW_LINE INDENT boundary . append ( a [ i ] [ n - 1 ] ) NEW_LINE DEDENT n -= 1 NEW_LINE if ( k < m ) : NEW_LINE INDENT for i in range ( n - 1 , l - 1 , - 1 ) : NEW_LINE INDENT boundary . append ( a [ m - 1 ] [ i ] ) NEW_LINE DEDENT m -= 1 NEW_LINE DEDENT if ( l < n ) : NEW_LINE INDENT for i in range ( m - 1 , k - 1 , - 1 ) : NEW_LINE INDENT boundary . append ( a [ i ] [ l ] ) NEW_LINE DEDENT l += 1 NEW_LINE DEDENT boundary . sort ( ) NEW_LINE ind = 0 NEW_LINE for i in range ( n_l , n_n ) : NEW_LINE INDENT a [ n_k ] [ i ] = boundary [ ind ] NEW_LINE ind += 1 NEW_LINE DEDENT n_k += 1 NEW_LINE for i in range ( n_k , n_m ) : NEW_LINE INDENT a [ i ] [ n_n - 1 ] = boundary [ ind ] NEW_LINE ind += 1 NEW_LINE DEDENT n_n -= 1 NEW_LINE if ( n_k < n_m ) : NEW_LINE INDENT for i in range ( n_n - 1 , n_l - 1 , - 1 ) : NEW_LINE INDENT a [ n_m - 1 ] [ i ] = boundary [ ind ] NEW_LINE ind += 1 NEW_LINE DEDENT n_m -= 1 NEW_LINE DEDENT if ( n_l < n_n ) : NEW_LINE INDENT for i in range ( n_m - 1 , n_k - 1 , - 1 ) : NEW_LINE INDENT a [ i ] [ n_l ] = boundary [ ind ] NEW_LINE ind += 1 NEW_LINE DEDENT n_l += 1 NEW_LINE DEDENT DEDENT printMatrix ( a ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT matrix = [ [ 9 , 7 , 4 , 5 ] , [ 1 , 6 , 2 , - 6 ] , [ 12 , 20 , 2 , 0 ] , [ - 5 , - 6 , 7 , - 2 ] ] NEW_LINE sortBoundaryWise ( matrix ) NEW_LINE DEDENT