📜  使用地图数据结构对 2D 矢量进行对角排序

📅  最后修改于: 2021-09-06 06:18:23             🧑  作者: Mango

给定一个二维向量mat[][]整数。任务是按照从左上角到右下角的递增顺序对向量的元素进行对角排序。
例子:

Input: mat[][] = 
{{9, 4, 2}, 
 {7, 4, 6},
 {2, 3, 3}}     
Output: 
3 4 2
3 4 6
2 7 9
Explanation:
There are 5 diagonals in this matrix:
1. {2} - No need to sort
2. {7, 3} - Sort - {3, 7}
3. {9, 4, 3} - Sort - {3, 4, 9}
4. {4, 6} - Already sorted
5. {2} - No need to sort



Input: mat[][] =  
{{ 4, 3, 2, 1 }, 
 { 3, 2, 1, 0 }, 
 { 2, 1, 1, 0 }, 
 { 0, 1, 2, 3 }}
Output: 
1 0 0 1 
1 2 1 2 
1 2 3 3 
0 2 3 4 

方法:

  1. 同一对角线上的所有元素具有相同的索引差i – j ,其中 i 是行号,j 是列号。所以我们可以使用映射来存储索引 i – j 处的每个对角线。
  2. 现在我们可以使用内置函数对地图的每个索引进行排序。
  3. 现在在原始矩阵中,我们可以插入存储在 map 中的矩阵的每条对角线。
  4. 最后,我们可以打印矩阵。

下面是上述方法的实现:

CPP
// C++ implementation to sort the
// diagonals of the matrix
 
#include 
using namespace std;
 
// Function to sort the
// diagonal of the matrix
void SortDiagonal(int mat[4][4],
                  int m, int n)
{
    // Map to store every diagonal
    // in different indices here
    // elements of same diagonal
    // will be stored in same index
    unordered_map > mp;
 
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            // Storing diagonal elements
            // in map
            mp[i - j].push_back(mat[i][j]);
        }
    }
 
    // To sort each diagonal in
    // ascending order
    for (int k = -(n - 1); k < m; k++)
    {
        sort(mp[k].begin(),
             mp[k].end());
    }
 
    // Loop to store every diagonal
    // in ascending order
    for (int i = m - 1; i >= 0; i--)
    {
        for (int j = n - 1; j >= 0; j--)
        {
            mat[i][j] = mp[i - j].back();
            mp[i - j].pop_back();
        }
    }
 
    // Loop to print the matrix
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++)
            cout << mat[i][j] << " ";
        cout << endl;
    }
}
 
// Driven Code
int main()
{
    int arr[4][4] = { { 4, 3, 2, 1 },
                    { 3, 2, 1, 0 },
                    { 2, 1, 1, 0 },
                    { 0, 1, 2, 3 } };
 
    // Sort the Diagonals
    SortDiagonal(arr, 4, 4);
 
    return 0;
}


Javascript


输出:
1 0 0 1 
1 2 1 2 
1 2 3 3 
0 2 3 4 

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live