Convert given Matrix into sorted Spiral Matrix | Python3 program to Convert given Matrix into sorted Spiral Matrix ; Function to convert the array to Spiral ; For Array pointer ; k - starting row index m - ending row index l - starting column index n - ending column index ; Print the first row from the remaining rows ; Print the last column from the remaining columns ; Print the last row from the remaining rows ; Print the first column from the remaining columns ; Function to convert 2D array to 1D array ; Store value 2D Matrix To 1D array ; Function to print the Matrix ; Print Spiral Matrix ; Function to sort the array ; Sort array Using InBuilt Function ; Function to Convert given Matrix into sorted Spiral Matrix ; Driver code
MAX = 1000 NEW_LINE def ToSpiral ( m , n , Sorted , a ) : NEW_LINE INDENT index = 0 NEW_LINE k = 0 NEW_LINE l = 0 NEW_LINE while ( k < m and l < n ) : NEW_LINE INDENT for i in range ( l , n , 1 ) : NEW_LINE INDENT a [ k ] [ i ] = Sorted [ index ] NEW_LINE index += 1 NEW_LINE DEDENT k += 1 NEW_LINE for i in range ( k , m , 1 ) : NEW_LINE INDENT a [ i ] [ n - 1 ] = Sorted [ index ] NEW_LINE index += 1 NEW_LINE DEDENT n -= 1 NEW_LINE if ( k < m ) : NEW_LINE INDENT i = n - 1 NEW_LINE while ( i >= l ) : NEW_LINE INDENT a [ m - 1 ] [ i ] = Sorted [ index ] NEW_LINE index += 1 NEW_LINE i -= 1 NEW_LINE DEDENT m -= 1 NEW_LINE DEDENT if ( l < n ) : NEW_LINE INDENT i = m - 1 NEW_LINE while ( i >= k ) : NEW_LINE INDENT a [ i ] [ l ] = Sorted [ index ] NEW_LINE index += 1 NEW_LINE i -= 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT DEDENT DEDENT def convert2Dto1D ( y , m , n ) : NEW_LINE INDENT index = 0 NEW_LINE x = [ 0 for i in range ( m * n ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT x [ index ] = y [ i ] [ j ] NEW_LINE index += 1 NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT def PrintMatrix ( a , m , n ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( a [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ' ' , end = " " ) NEW_LINE DEDENT DEDENT def SortArray ( x ) : NEW_LINE INDENT x . sort ( reverse = False ) NEW_LINE return x NEW_LINE DEDENT def convertMatrixToSortedSpiral ( y , m , n ) : NEW_LINE INDENT a = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE x = [ 0 for i in range ( 15 ) ] NEW_LINE x = convert2Dto1D ( y , m , n ) NEW_LINE x = SortArray ( x ) NEW_LINE ToSpiral ( m , n , x , a ) NEW_LINE PrintMatrix ( a , m , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 4 NEW_LINE n = 3 NEW_LINE y = [ [ 2 , 5 , 12 ] , [ 22 , 45 , 55 ] , [ 1 , 6 , 8 ] , [ 13 , 56 , 10 ] ] NEW_LINE convertMatrixToSortedSpiral ( y , m , n ) NEW_LINE DEDENT