Modify a given matrix by placing sorted boundary elements in clockwise manner | Java 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
import java . util . * ; class GFG { static void printMatrix ( ArrayList < ArrayList < Integer > > a ) { for ( int i = 0 ; i < a . size ( ) ; i ++ ) { for ( int j = 0 ; j < a . get ( i ) . size ( ) ; j ++ ) { System . out . print ( a . get ( i ) . get ( j ) + " ▁ " ) ; } System . out . println ( ) ; } } static void sortBoundaryWise ( ArrayList < ArrayList < Integer > > a ) { int i , k = 0 , l = 0 ; int m = a . size ( ) , n = a . get ( 0 ) . size ( ) ; int n_i , n_k = 0 , n_l = 0 , n_m = m , n_n = n ; while ( k < m && l < n ) { ArrayList < Integer > boundary = new ArrayList < Integer > ( ) ; for ( i = l ; i < n ; ++ i ) { boundary . add ( a . get ( k ) . get ( i ) ) ; } k ++ ; for ( i = k ; i < m ; ++ i ) { boundary . add ( a . get ( i ) . get ( n - 1 ) ) ; } n -- ; if ( k < m ) { for ( i = n - 1 ; i >= l ; -- i ) { boundary . add ( a . get ( m - 1 ) . get ( i ) ) ; } m -- ; } if ( l < n ) { for ( i = m - 1 ; i >= k ; -- i ) { boundary . add ( a . get ( i ) . get ( l ) ) ; } l ++ ; } Collections . sort ( boundary ) ; int ind = 0 ; for ( i = n_l ; i < n_n ; ++ i ) { a . get ( n_k ) . set ( i , boundary . get ( ind ) ) ; ind ++ ; } n_k += 1 ; for ( i = n_k ; i < n_m ; ++ i ) { a . get ( i ) . set ( n_n - 1 , boundary . get ( ind ) ) ; ind ++ ; } n_n -- ; if ( n_k < n_m ) { for ( i = n_n - 1 ; i >= n_l ; -- i ) { a . get ( n_m - 1 ) . set ( i , boundary . get ( ind ) ) ; ind ++ ; } n_m -- ; } if ( n_l < n_n ) { for ( i = n_m - 1 ; i >= n_k ; -- i ) { a . get ( i ) . set ( n_l , boundary . get ( ind ) ) ; ind ++ ; } n_l ++ ; } } printMatrix ( a ) ; } public static void main ( String args [ ] ) { ArrayList < ArrayList < Integer > > matrix = new ArrayList < ArrayList < Integer > > ( ) ; ArrayList < Integer > list1 = new ArrayList < Integer > ( Arrays . asList ( 9 , 7 , 4 , 5 ) ) ; ArrayList < Integer > list2 = new ArrayList < Integer > ( Arrays . asList ( 1 , 6 , 2 , - 6 ) ) ; ArrayList < Integer > list3 = new ArrayList < Integer > ( Arrays . asList ( 12 , 20 , 2 , 0 ) ) ; ArrayList < Integer > list4 = new ArrayList < Integer > ( Arrays . asList ( - 5 , - 6 , 7 , - 2 ) ) ; matrix . add ( list1 ) ; matrix . add ( list2 ) ; matrix . add ( list3 ) ; matrix . add ( list4 ) ; sortBoundaryWise ( matrix ) ; } }