📌  相关文章
📜  交换给定矩阵的上下三角一半

📅  最后修改于: 2021-04-27 19:08:07             🧑  作者: Mango

给定尺寸为N * N的正方形矩阵mat [] [] ,任务是打印在交换给定矩阵的上,下三角两半的横向倒置图像后可获得的矩阵。

例子:

方法:请按照以下步骤解决问题:

  • 初始化向量数组upDiagonallowDiagonal ,分别存储来自下半三角形和上半三角形的矩阵元素的元素。
  • 使用变量ij分别遍历行和列遍历给定的矩阵,然后执行以下步骤:
    • 如果当前元素在主对角线上,则从此迭代继续。
    • 否则,如果当前元素存在于三角形的上半部分,则将该元素添加到索引为abs(i – j)的upDiagonal上。
    • 否则,将当前元素添加到索引为abs(i – j)的lowDiagonal上。
  • 现在,再次穿过所述基质,并与来自下半和反之亦然的端部的元件替代任何元素存在于上半
  • 完成上述步骤后,打印所得矩阵。

下面是上述方法的实现:

C++
4
7 8


Java
6
 3 2


Python3
1  2  3    1  8  7
4  5  6 to 6  5  4
7  8  9    3  2  9


C#
1  2  3    6  5  4
1  8  7 to 7  8  9
4  5  6    3  2  9


输出:
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to swap laterally inverted
// images of upper and lower triangular
// halves of a given matrix
void ReverseSwap(vector >& mat, int n)
{
    // Store the matrix elements from
    // upper & lower triangular halves
    vector lowerEle[n];
    vector upperEle[n];
 
    int index;
 
    // Traverse the matrix mat[][]
    for (int i = 0; i < n; i++) {
 
        for (int j = 0; j < n; j++) {
 
            // Find the index
            index = abs(i - j);
 
            // If current element lies
            // on the principal diagonal
            if (i == j) {
                continue;
            }
 
            // If current element lies
            // below the principal diagonal
            else if (j < i) {
                lowerEle[index].push_back(
                    mat[i][j]);
            }
 
            // If current element lies
            // above the principal diagonal
            else {
                upperEle[index].push_back(
                    mat[i][j]);
            }
        }
    }
 
    // Traverse again to swap values
    for (int i = 0; i < n; i++) {
 
        for (int j = 0; j < n; j++) {
 
            // Find the index
            index = abs(i - j);
 
            // Principal diagonal
            if (i == j) {
                continue;
            }
 
            // Below main diagonal
            else if (j < i) {
 
                mat[i][j] = upperEle[index].back();
                upperEle[index].pop_back();
            }
 
            // Above main diagonal
            else {
                mat[i][j] = lowerEle[index].back();
                lowerEle[index].pop_back();
            }
        }
    }
 
    // Traverse the matrix and print
    for (int i = 0; i < n; i++) {
 
        for (int j = 0; j < n; j++) {
 
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    // Given Matrix mat[][]
    vector > mat = { { 1, 2 },
                                 { 4, 5 } };
 
    int N = mat.size();
 
    // Swap the upper and lower
    // triangular halves
    ReverseSwap(mat, N);
 
    return 0;
}

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