给定大小为M * N的矩阵mat [] [] ,任务是仅按顺时针方向对矩阵的边界元素进行排序,并在再次排序后打印矩阵。
例子:
Input: M = 4, N = 5, Below is the given matrix:
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
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)
方法:这个想法是将给定矩阵的所有边界元素存储在一个数组中,并对这个数组进行排序,然后使用该排序后的数组作为边界元素,简单地打印新矩阵。
详细步骤如下:
- 遍历给定的矩阵并将所有边界元素推入数组A [] 。
- 以升序对数组A []进行排序。
- 使用数组A []的前N个元素打印第一行。
- 从第二行到倒数第二行,首先从A []的结尾打印一个元素,然后从原始矩阵打印N-2个中间元素,最后从A []的前面打印单个元素。
- 对于最后一行,以相反的顺序打印A []中尚未打印的中间元素。
下面是上述方法的实现:
C++
1 2 3 4 0
1 1 1 1 2
1 2 2 2 4
1 9 3 1 7
Python3
4 2 8 0
2 6 9 8
0 3 1 7
// C++ program for the above approach
#include
using namespace std;
void printMatrix(int grid[][5], int m, int n)
{
vector 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 Code
int 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.
时间复杂度: O(M * N)
辅助空间: O(M + N)