Modify a given matrix by placing sorted boundary elements in clockwise manner | C # program for the above approach ; 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
using System ; using System . Collections . Generic ; class GFG { static void printMatrix ( List < List < int > > a ) { foreach ( List < int > x in a ) { foreach ( int y in x ) { Console . Write ( y + " ▁ " ) ; } Console . WriteLine ( ) ; } } static void sortBoundaryWise ( List < List < int > > a ) { int i , k = 0 , l = 0 ; int m = a . Count , n = a [ 0 ] . Count ; int n_k = 0 , n_l = 0 , n_m = m , n_n = n ; while ( k < m && l < n ) { List < int > boundary = new List < int > ( ) ; for ( i = l ; i < n ; ++ i ) { boundary . Add ( a [ k ] [ i ] ) ; } k ++ ; for ( i = k ; i < m ; ++ i ) { boundary . Add ( a [ i ] [ n - 1 ] ) ; } n -- ; if ( k < m ) { for ( i = n - 1 ; i >= l ; -- i ) { boundary . Add ( a [ m - 1 ] [ i ] ) ; } m -- ; } if ( l < n ) { for ( i = m - 1 ; i >= k ; -- i ) { boundary . Add ( a [ i ] [ l ] ) ; } l ++ ; } boundary . Sort ( ) ; int ind = 0 ; for ( i = n_l ; i < n_n ; ++ i ) { a [ n_k ] [ i ] = boundary [ ind ++ ] ; } n_k ++ ; for ( i = n_k ; i < n_m ; ++ i ) { a [ i ] [ n_n - 1 ] = boundary [ ind ++ ] ; } n_n -- ; if ( n_k < n_m ) { for ( i = n_n - 1 ; i >= n_l ; -- i ) { a [ n_m - 1 ] [ i ] = boundary [ ind ++ ] ; } n_m -- ; } if ( n_l < n_n ) { for ( i = n_m - 1 ; i >= n_k ; -- i ) { a [ i ] [ n_l ] = boundary [ ind ++ ] ; } n_l ++ ; } } printMatrix ( a ) ; } static void Main ( ) { List < List < int > > matrix = new List < List < int > > ( ) ; matrix . Add ( new List < int > ( new int [ ] { 9 , 7 , 4 , 5 } ) ) ; matrix . Add ( new List < int > ( new int [ ] { 1 , 6 , 2 , - 6 } ) ) ; matrix . Add ( new List < int > ( new int [ ] { 12 , 20 , 2 , 0 } ) ) ; matrix . Add ( new List < int > ( new int [ ] { - 5 , - 6 , 7 , - 2 } ) ) ; sortBoundaryWise ( matrix ) ; } }