📌  相关文章
📜  通过按顺时针方向放置排序的边界元素来修改给定的矩阵

📅  最后修改于: 2021-04-17 14:21:38             🧑  作者: Mango

给定N * N的平方矩阵A [] [] 任务是对矩阵的边界元素从最外边界到最内边界进行排序,并将它们按顺时针方向放置。

例子:

方法:想法是使用边界变量来获取当前边界元素并将其存储在数组中。然后,按升序对数组进行排序,然后将已排序的元素按顺时针方向放回到矩阵中。
请按照以下步骤解决问题:

  • 初始化变量,例如k,m,ln ,分别代表开始行索引,结束行索引,开始列索引和结束列索引。
  • 进行迭代,直到访问所有的循环平方。
    • 在每个外部循环遍历中,以顺时针方式将正方形的元素存储在一个数组中,例如V。
    • 推入V中的顶部行,即k行的从列索引元件推到n。增加k的数量
    • V中推右列,即将n – 1列的元素从行索引k推到m 。减少计数n
    • 推底部行,即,如果k 则推M-1行的元素从塔指数n – 1。减少m的数量
    • 推左栏,即,如果则推从行索引M的元素– 1k。增加l的数量
    • 按升序对数组V排序。
    • 重复上述步骤,并使用V中排序的元素更新矩阵的元素。
  • 完成矩阵遍历后,打印修改后的矩阵A。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to print the elements
// of the matrix in row-wise manner
void printMatrix(vector > a)
{
    for (auto x : a) {
        for (auto y : x) {
            cout << y << " ";
        }
        cout << "\n";
    }
}
 
// Function to sort boundary elements
// of a matrix starting from the outermost
// to the innermost boundary and place them
// in a clockwise manner
void sortBoundaryWise(vector > a)
{
    /*  k - starting row index
        m - ending row index
        l - starting column index
        n - ending column index
        i - iterator
      */
    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) {
 
        // Stores the current
        // boundary elements
        vector boundary;
 
        // Push the first row
        for (i = l; i < n; ++i) {
            boundary.push_back(a[k][i]);
        }
        k++;
 
        // Push the last column
        for (i = k; i < m; ++i) {
            boundary.push_back(a[i][n - 1]);
        }
        n--;
 
        // Push the last row
        if (k < m) {
            for (i = n - 1; i >= l; --i) {
                boundary.push_back(a[m - 1][i]);
            }
            m--;
        }
 
        // Push the first column
        if (l < n) {
            for (i = m - 1; i >= k; --i) {
                boundary.push_back(a[i][l]);
            }
            l++;
        }
 
        // Sort the boundary elements
        sort(boundary.begin(), boundary.end());
        int ind = 0;
 
        // Update the current boundary
        // with sorted elements
 
        // Update the first row
        for (i = n_l; i < n_n; ++i) {
            a[n_k][i] = boundary[ind++];
        }
        n_k++;
 
        // Update the last column
        for (i = n_k; i < n_m; ++i) {
            a[i][n_n - 1] = boundary[ind++];
        }
        n_n--;
 
        // Update the last row
        if (n_k < n_m) {
            for (i = n_n - 1; i >= n_l; --i) {
                a[n_m - 1][i] = boundary[ind++];
            }
            n_m--;
        }
 
        // Update the first column
        if (n_l < n_n) {
            for (i = n_m - 1; i >= n_k; --i) {
                a[i][n_l] = boundary[ind++];
            }
            n_l++;
        }
    }
 
    // Print the resultant matrix
    printMatrix(a);
}
 
// Driver Code
int main()
{
    // Given matrix
    vector > matrix = { { 9, 7, 4, 5 },
                                    { 1, 6, 2, -6 },
                                    { 12, 20, 2, 0 },
                                    { -5, -6, 7, -2 } };
 
    sortBoundaryWise(matrix);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to print the elements
// of the matrix in row-wise manner
static void printMatrix(ArrayList> 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();
    }
}
 
// Function to sort boundary elements
// of a matrix starting from the outermost
// to the innermost boundary and place them
// in a clockwise manner
static void sortBoundaryWise(ArrayList> a)
{
    /*  k - starting row index
        m - ending row index
        l - starting column index
        n - ending column index
        i - iterator
      */
    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)
    {
         
        // Stores the current
        // boundary elements
        ArrayList boundary = new ArrayList();
 
        // Push the first row
        for(i = l; i < n; ++i)
        {
            boundary.add(a.get(k).get(i));
        }
        k++;
 
        // Push the last column
        for(i = k; i < m; ++i)
        {
            boundary.add(a.get(i).get(n - 1));
        }
        n--;
 
        // Push the last row
        if (k < m)
        {
            for(i = n - 1; i >= l; --i)
            {
                boundary.add(a.get(m - 1).get(i));
            }
            m--;
        }
 
        // Push the first column
        if (l < n)
        {
            for(i = m - 1; i >= k; --i)
            {
                boundary.add(a.get(i).get(l));
            }
            l++;
        }
 
        // Sort the boundary elements
        Collections.sort(boundary);  
        int ind = 0;
 
        // Update the current boundary
        // with sorted elements
 
        // Update the first row
        for(i = n_l; i < n_n; ++i)
        {
            a.get(n_k).set(i, boundary.get(ind));
            ind++;
        }
        n_k += 1;
 
        // Update the last column
        for(i = n_k; i < n_m; ++i)
        {
            a.get(i).set(n_n - 1, boundary.get(ind));
             ind++;
        }
        n_n--;
 
        // Update the last row
        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--;
        }
         
        // Update the first column
        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++;
        }
    }
 
    // Print the resultant matrix
    printMatrix(a);
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given matrix
    ArrayList<
    ArrayList> matrix = new ArrayList<
                                     ArrayList>();
    ArrayList list1 = new ArrayList(
        Arrays.asList(9, 7, 4, 5));
    ArrayList list2 = new ArrayList(
        Arrays.asList(1, 6, 2, -6));
    ArrayList list3 = new ArrayList(
        Arrays.asList(12, 20, 2, 0));
    ArrayList list4 = new ArrayList(
        Arrays.asList(-5, -6, 7, -2));
         
    matrix.add(list1);
    matrix.add(list2);
    matrix.add(list3);
    matrix.add(list4);
 
    sortBoundaryWise(matrix);
}
}
 
// This code is contributed by ipg2016107


Python3
# Python3 program for the above approach
 
# Function to print the elements
# of the matrix in row-wise manner
def printMatrix(a):
    for x in a:
        for y in x:
            print(y, end = " ")
 
        print()
 
# Function to sort boundary elements
# of a matrix starting from the outermost
# to the innermost boundary and place them
# in a clockwise manner
def sortBoundaryWise(a):
   
    '''  k - starting row index
        m - ending row index
        l - starting column index
        n - ending column index
        i - iterator
      '''
    k = 0
    l = 0
    m = len(a)
    n = len(a[0])
    n_k = 0
    n_l = 0
    n_m = m
    n_n = n
 
    while (k < m and l < n):
 
        # Stores the current
        # boundary elements
        boundary = []
 
        # Push the first row
        for i in range(l, n):
            boundary.append(a[k][i])
        k += 1
 
        # Push the last column
        for i in range(k, m):
            boundary.append(a[i][n - 1])
        n -= 1
 
        # Push the last row
        if (k < m):
            for i in range(n - 1,  l - 1, -1):
                boundary.append(a[m - 1][i])
            m -= 1
 
        # Push the first column
        if (l < n):
            for i in range(m - 1, k - 1, -1):
                boundary.append(a[i][l])
            l += 1
 
        # Sort the boundary elements
        boundary.sort()
        ind = 0
 
        # Update the current boundary
        # with sorted elements
 
        # Update the first row
        for i in range(n_l, n_n):
            a[n_k][i] = boundary[ind]
            ind += 1
 
        n_k += 1
 
        # Update the last column
        for i in range(n_k, n_m):
            a[i][n_n - 1] = boundary[ind]
            ind += 1
        n_n -= 1
 
        # Update the last row
        if (n_k < n_m):
            for i in range(n_n - 1, n_l - 1, -1):
                a[n_m - 1][i] = boundary[ind]
                ind += 1
 
            n_m -= 1
 
        # Update the first column
        if (n_l < n_n):
            for i in range(n_m - 1, n_k - 1, -1):
                a[i][n_l] = boundary[ind]
                ind += 1
            n_l += 1
 
    # Print the resultant matrix
    printMatrix(a)
 
# Driver Code
if __name__ == "__main__":
 
    # Given matrix
    matrix = [[9, 7, 4, 5],
              [1, 6, 2, -6],
              [12, 20, 2, 0],
              [-5, -6, 7, -2]]
 
    sortBoundaryWise(matrix)
 
    # This code is contributed by ukasp.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
 
class GFG
{
 
  // Function to print the elements
  // of the matrix in row-wise manner
  static void printMatrix(List> a)
  {
    foreach(List x in a) {
      foreach(int y in x) {
        Console.Write(y + " ");
      }
      Console.WriteLine();
    }
  }
 
  // Function to sort boundary elements
  // of a matrix starting from the outermost
  // to the innermost boundary and place them
  // in a clockwise manner
  static void sortBoundaryWise(List> a)
  {
    /*  k - starting row index
            m - ending row index
            l - starting column index
            n - ending column index
            i - iterator
          */
    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) {
 
      // Stores the current
      // boundary elements
      List boundary = new List();
 
      // Push the first row
      for (i = l; i < n; ++i) {
        boundary.Add(a[k][i]);
      }
      k++;
 
      // Push the last column
      for (i = k; i < m; ++i) {
        boundary.Add(a[i][n - 1]);
      }
      n--;
 
      // Push the last row
      if (k < m) {
        for (i = n - 1; i >= l; --i) {
          boundary.Add(a[m - 1][i]);
        }
        m--;
      }
 
      // Push the first column
      if (l < n) {
        for (i = m - 1; i >= k; --i) {
          boundary.Add(a[i][l]);
        }
        l++;
      }
 
      // Sort the boundary elements
      boundary.Sort();
      int ind = 0;
 
      // Update the current boundary
      // with sorted elements
 
      // Update the first row
      for (i = n_l; i < n_n; ++i) {
        a[n_k][i] = boundary[ind++];
      }
      n_k++;
 
      // Update the last column
      for (i = n_k; i < n_m; ++i) {
        a[i][n_n - 1] = boundary[ind++];
      }
      n_n--;
 
      // Update the last row
      if (n_k < n_m) {
        for (i = n_n - 1; i >= n_l; --i) {
          a[n_m - 1][i] = boundary[ind++];
        }
        n_m--;
      }
 
      // Update the first column
      if (n_l < n_n) {
        for (i = n_m - 1; i >= n_k; --i) {
          a[i][n_l] = boundary[ind++];
        }
        n_l++;
      }
    }
 
    // Print the resultant matrix
    printMatrix(a);
  }
 
  // Driver code
  static void Main()
  {
    // Given matrix
    List> matrix = new List>();
    matrix.Add(new List(new int[]{9, 7, 4, 5}));
    matrix.Add(new List(new int[]{1, 6, 2, -6}));
    matrix.Add(new List(new int[]{12, 20, 2, 0}));
    matrix.Add(new List(new int[]{-5, -6, 7, -2}));
 
    sortBoundaryWise(matrix);
  }
}
 
// This code is contributed by divyeshrabadiya07.


输出
-6 -6 -5 -2 
12 2 2 0 
9 20 6 1 
7 7 5 4 

时间复杂度: O(N 3 * log(N))
辅助空间: O(N 2 )