Convert given Matrix into sorted Spiral Matrix | Java 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
import java . util . * ; public class TwistedMatrix { static int MAX = 1000 ; static void ToSpiral ( int m , int n , int Sorted [ ] , int a [ ] [ ] ) { int index = 0 ; int k = 0 , l = 0 ; while ( k < m && l < n ) { for ( int i = l ; i < n ; ++ i ) { a [ k ] [ i ] = Sorted [ index ] ; index ++ ; } k ++ ; for ( int i = k ; i < m ; ++ i ) { a [ i ] [ n - 1 ] = Sorted [ index ] ; index ++ ; } n -- ; if ( k < m ) { for ( int i = n - 1 ; i >= l ; -- i ) { a [ m - 1 ] [ i ] = Sorted [ index ] ; index ++ ; } m -- ; } if ( l < n ) { for ( int i = m - 1 ; i >= k ; -- i ) { a [ i ] [ l ] = Sorted [ index ] ; index ++ ; } l ++ ; } } } public static int [ ] convert2Dto1D ( int y [ ] [ ] , int m , int n ) { int index = 0 ; int x [ ] = new int [ m * n ] ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { x [ index ] = y [ i ] [ j ] ; index ++ ; } } return x ; } public static void PrintMatrix ( int a [ ] [ ] , int m , int n ) { for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { System . out . print ( a [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static int [ ] SortArray ( int x [ ] ) { Arrays . sort ( x ) ; return x ; } public static void convertMatrixToSortedSpiral ( int y [ ] [ ] , int m , int n ) { int a [ ] [ ] = new int [ MAX ] [ MAX ] ; int x [ ] = new int [ m * n ] ; x = convert2Dto1D ( y , m , n ) ; x = SortArray ( x ) ; ToSpiral ( m , n , x , a ) ; PrintMatrix ( a , m , n ) ; } public static void main ( String [ ] args ) { int m = 4 , n = 3 ; int y [ ] [ ] = { { 2 , 5 , 12 } , { 22 , 45 , 55 } , { 1 , 6 , 8 } , { 13 , 56 , 10 } } ; convertMatrixToSortedSpiral ( y , m , n ) ; } }