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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMatrix ( vector < vector < int > > a ) { for ( auto x : a ) { for ( auto y : x ) { cout << y << " ▁ " ; } cout << " STRNEWLINE " ; } } void sortBoundaryWise ( vector < vector < int > > a ) { int i , k = 0 , l = 0 ; int m = a . size ( ) , n = a [ 0 ] . size ( ) ; int n_i , n_k = 0 , n_l = 0 , n_m = m , n_n = n ; while ( k < m && l < n ) { vector < int > boundary ; for ( i = l ; i < n ; ++ i ) { boundary . push_back ( a [ k ] [ i ] ) ; } k ++ ; for ( i = k ; i < m ; ++ i ) { boundary . push_back ( a [ i ] [ n - 1 ] ) ; } n -- ; if ( k < m ) { for ( i = n - 1 ; i >= l ; -- i ) { boundary . push_back ( a [ m - 1 ] [ i ] ) ; } m -- ; } if ( l < n ) { for ( i = m - 1 ; i >= k ; -- i ) { boundary . push_back ( a [ i ] [ l ] ) ; } l ++ ; } sort ( boundary . begin ( ) , boundary . end ( ) ) ; 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 ) ; } int main ( ) { vector < vector < int > > matrix = { { 9 , 7 , 4 , 5 } , { 1 , 6 , 2 , -6 } , { 12 , 20 , 2 , 0 } , { -5 , -6 , 7 , -2 } } ; sortBoundaryWise ( matrix ) ; return 0 ; }