Sorting boundary elements of a matrix

30 May, 2022
Given a matrix mat[][] of size M*N, the task is to sort only the border elements of the matrix in the clockwise direction and print the matrix after sorting again.
Examples:  
Input: M = 4, N = 5, Below is the given matrix: 
1 2 3 4 0 
1 1 1 1 2  
1 2 2 2 4 
1 9 3 1 7
Output: 0 1 1 1 1 9 1 1 1 1 7 2 2 2 2 4 4 3 3 2 Explanation: For given matrix, border elements are: (1, 2, 3, 4, 0, 2, 4, 7, 1, 3, 9, 1, 1, 1) After sorting in clockwise order: (0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 7, 9)
Input: M = 3, N = 4 
4 2 8 0 
2 6 9 8 
0 3 1 7
Output: 0 0 1 2 8 6 9 2 8 7 4 3 Explanation: For given matrix, border elements are: (4, 2, 8, 0, 8, 7, 1, 3, 0, 2) After sorting in clockwise order: (0, 0, 1, 2, 2, 3, 4, 7, 8, 8)  
Approach: The idea is to store all border elements of the given matrix in an array and sort this array then simply print the new matrix using this sorted array as the border elements.
Detailed steps are as follows:  
Traverse the given matrix and push all the boundary elements to an array A[].
Sort array A[] in ascending order.
Print first row using first N elements of array A[].
From second row to second-last row, first print a single element from end of A[], then print N-2 middle elements from original matrix and finally a single element from the front of A[].
For last row, print middle elements from A[] which are still not printed, in reverse order.
Below is the implementation of the above approach: 
C++
Java
Python3
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;void printMatrix(int grid[][5], int m, int n){  vector<int> A;   // Appending border elements  for (int i = 0; i < m; i++)  {    for (int j = 0; j < n; j++)    {      if (j == n - 1 || (i == m - 1) || j == 0          || i == 0)        A.push_back(grid[i][j]);    }  }   // Sorting the list  sort(A.begin(), A.end());   // Printing first row with  // first N elements from A  for (int i = 0; i < n; i++)    cout << A[i] << " ";  cout << endl;  // print(*A[:n])   // Printing N-2 rows  for (int i = 0; i < m - 2; i++)  {     // Print elements from last    cout << A[A.size() - i - 1] << " ";     // Print middle elements    // from original matrix    for (int j = 1; j < n - 1; j++)      cout << grid[i + 1][j] << " ";     // Print elements from front    cout << (A[n + i]) << endl;  }   // Printing last row  reverse(A.begin() + n + m - 2,          A.begin() + n + m + n - 2);  for (int i = n + m - 2; i < n + m - 2 + n; i++)    cout << A[i] << " ";  //[n + m - 2:n + m - 2 + n] << endl;} // Driver Codeint main(){  // Dimensions of a Matrix  int m = 4, n = 5;   // Given Matrix  int grid[][5] = { { 1, 2, 3, 4, 0 },                   { 1, 1, 1, 1, 2 },                   { 1, 2, 2, 2, 4 },                   { 1, 9, 3, 1, 7 } };   // Function Call  printMatrix(grid, m, n);  return 0;} // This code is contributed by chitranayal.
// JAVA program for the above approachimport java.util.*;class GFG{   public static void printMatrix(int[][] grid, int m, int n)  {    ArrayList<Integer> A = new ArrayList<>();     // Appending border elements    for (int i = 0; i < m; i++)    {      for (int j = 0; j < n; j++)      {        if (j == n - 1 || (i == m - 1) || j == 0            || i == 0)          A.add(grid[i][j]);      }    }     // Sorting the list    Collections.sort(A);       // Printing first row with    // first N elements from A    for (int i = 0; i < n; i++)      System.out.print(A.get(i)+" ");    System.out.print('\n');    // print(*A[:n])     // Printing N-2 rows    for (int i = 0; i < m - 2; i++)    {       // Print elements from last      System.out.print(A.get(A.size() - i - 1)+" ");       // Print middle elements      // from original matrix      for (int j = 1; j < n - 1; j++)        System.out.print(grid[i + 1][j]+" ");       // Print elements from front      System.out.println(A.get(n + i));    }     // Printing last row    Collections.reverse(A.subList( n + m - 2 , n + m - 2 + n ) ) ;    for (int i = n + m - 2; i < n + m - 2 + n; i++)      System.out.print(A.get(i)+" ");     //[n + m - 2:n + m - 2 + n] << endl;  }   /* Driver program to test above function */  public static void main(String[] args)  {    // Dimensions of a Matrix    int m = 4, n = 5;     // Given Matrix    int[][] grid = { { 1, 2, 3, 4, 0 },                    { 1, 1, 1, 1, 2 },                    { 1, 2, 2, 2, 4 },                    { 1, 9, 3, 1, 7 } };     // Function Call    printMatrix(grid, m, n);  }} // This code is contributed by Pushpesh Raj.
# Python program for the above approach def printMatrix(grid, m, n):         A =[]     # Appending border elements    for i in range(m):        for j in range(n):            if j == n-1 or (i == m-1                ) or j == 0 or i == 0:                A.append(grid[i][j])                     # Sorting the list         A.sort()      # Printing first row with    # first N elements from A    print(*A[:n])      # Printing N-2 rows    for i in range(m-2):                 # Print elements from last        print(A[len(A)-i-1],                          end =" ")        # Print middle elements        # from original matrix        for j in range(1, n-1):            print(grid[i + 1][j],                          end =" ")                                  # Print elements from front        print(A[n + i])     # Printing last row    print(*reversed(A[n + m-2:n + m-2 + n])) # Driver Code # Dimensions of a Matrixm, n = 4, 5 # Given Matrixgrid =[[1, 2, 3, 4, 0],       [1, 1, 1, 1, 2],       [1, 2, 2, 2, 4],       [1, 9, 3, 1, 7]] # Function CallprintMatrix(grid, m, n)
<script> // Javascript program for the above approachfunction printMatrix(grid, m, n){    let A = [];         // Appending border elements    for(let i = 0; i < m; i++)    {        for(let j = 0; j < n; j++)        {            if (j == n - 1 || (i == m - 1) ||                j == 0 || i == 0)                A.push(grid[i][j]);        }    }         // Sorting the list    A.sort(function(a, b){return a - b;});         // Printing first row with    // first N elements from A    for(let i = 0; i < n; i++)        document.write(A[i] + " ");             document.write("<br>")    // print(*A[:n])         // Printing N-2 rows    for(let i = 0; i < m - 2; i++)    {             // Print elements from last        document.write(A[A.length - i - 1] + " ");                 // Print middle elements        // from original matrix        for(let j = 1; j < n - 1; j++)            document.write(grid[i + 1][j] + " ");                 // Print elements from front        document.write(A[n + i] + "<br>")    }         // Printing last row    document.write(A.slice(        n + m - 2, n + m - 2 + n).reverse().join(" "));    //[n + m - 2:n + m - 2 + n] << endl;} // Driver Code // Dimensions of a Matrixlet m = 4, n = 5; // Given Matrixlet grid = [ [ 1, 2, 3, 4, 0 ],             [ 1, 1, 1, 1, 2 ],             [ 1, 2, 2, 2, 4 ],             [ 1, 9, 3, 1, 7 ] ];                    // Function CallprintMatrix(grid, m, n);   // This code is contributed by avanitrachhadiya2155 </script>
0 1 1 1 1
9 1 1 1 1
7 2 2 2 2
4 4 3 3 2
 
Time Complexity: O(M*N) Auxiliary Space: O(M+N) 
ukasp
avanitrachhadiya2155
pushpeshrajdx01
Sorting Quiz
Matrix
Pattern Searching
Sorting
Sorting
Matrix
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unique paths in a Grid with Obstacles
Find the longest path in a matrix with given constraints
Find median in row wise sorted matrix
Zigzag (or diagonal) traversal of Matrix
Traverse a given Matrix using Recursion
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if a string is substring of another
Check if an URL is valid or not using Regular Expression
Boyer Moore Algorithm for Pattern Searching