Intercambiar las mitades triangulares superior e inferior de una Array dada

Dada una array cuadrada mat[][] de dimensiones N * N , la tarea es imprimir la array que se puede obtener después de intercambiar las imágenes lateralmente invertidas de las mitades triangulares superior e inferior de una array dada.

Considere la array mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
La imagen lateral de la mitad triangular inferior de la array

4
7 8

La imagen lateral de la mitad triangular superior de la array.

 6
 3 2

Por lo tanto, es necesario realizar el siguiente reordenamiento de la array

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

Ejemplos:

Entrada: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Salida:
1 8 7
6 5 4
3 2 9
Explicación:

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

Entrada: mat[][] = {{1, 2}, {4, 5}}
Salida:
1 4
2 5

Enfoque: siga los pasos a continuación para resolver el problema:

  • Inicialice una array de vectores , upDiagonal y lowDiagonal , para almacenar los elementos de los elementos de la array de las mitades triangulares inferior y superior, respectivamente.
  • Recorra la array dada usando las variables i y j para filas y columnas respectivamente y realice los siguientes pasos:
    • Si el elemento actual está en la diagonal principal, continúe desde esta iteración.
    • De lo contrario, si el elemento actual está presente en la mitad triangular superior, agregue este elemento a upDiagonal en el índice abs(i – j) .
    • De lo contrario, agregue el elemento actual a lowDiagonal en el índice abs(i – j) .
  • Ahora, atraviese nuevamente la array y reemplace cualquier elemento presente en la mitad superior con el elemento del extremo de la mitad inferior y viceversa.
  • Después de completar los pasos anteriores, imprima la array resultante.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to swap laterally inverted
// images of upper and lower triangular
// halves of a given matrix
void ReverseSwap(vector<vector<int> >& mat, int n)
{
    // Store the matrix elements from
    // upper & lower triangular halves
    vector<int> lowerEle[n];
    vector<int> 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<vector<int> > mat = { { 1, 2 },
                                 { 4, 5 } };
 
    int N = mat.size();
 
    // Swap the upper and lower
    // triangular halves
    ReverseSwap(mat, N);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to swap laterally inverted
// images of upper and lower triangular
// halves of a given matrix
static void ReverseSwap(int[][] mat, int n)
{
     
    // Store the matrix elements from
    // upper & lower triangular halves
    int[] lowerEle = new int[n];
    int[] upperEle = new int[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 = Math.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] = mat[i][j];
            }
 
            // If current element lies
            // above the principal diagonal
            else
            {
                upperEle[index] = 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 = Math.abs(i - j);
 
            // Principal diagonal
            if (i == j)
            {
                continue;
            }
 
            // Below main diagonal
            else if (j < i)
            {
                mat[i][j] = upperEle[index];
            }
 
            // Above main diagonal
            else
            {
                mat[i][j] = lowerEle[index--];
            }
        }
    }
 
    // Traverse the matrix and print
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            System.out.print(mat[i][j] + " ");
        }
        System.out.println();
    }
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given Matrix mat[][]
    int[][] mat = new int[][]{ { 1, 2 }, { 4, 5 } };
 
    int N = mat.length;
 
    // Swap the upper and lower
    // triangular halves
    ReverseSwap(mat, N);
}
}
 
// This code is contributed by Dharanendra L V

Python3

# Python3 program for the above approach
 
# Function to swap laterally inverted
# images of upper and lower triangular
# halves of a given matrix
def ReverseSwap(mat, n):
     
    # Store the matrix elements from
    # upper & lower triangular halves
    lowerEle = [[] for i in range(n)]
    upperEle = [[] for i in range(n)]
 
    index = 0
 
    # Traverse the matrix mat[][]
    for i in range(n):
        for j in range(n):
             
            # 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
            elif (j < i):
                lowerEle[index].append(mat[i][j])
 
            # If current element lies
            # above the principal diagonal
            else:
                upperEle[index].append(mat[i][j])
 
    # Traverse again to swap values
    for i in range(n):
        for j in range(n):
 
            # Find the index
            index = abs(i - j)
 
            # Principal diagonal
            if (i == j):
                continue
 
            # Below main diagonal
            elif (j < i):
                mat[i][j] = upperEle[index][-1]
                del upperEle[index][-1]
                 
            # Above main diagonal
            else:
                mat[i][j] = lowerEle[index][-1]
                del lowerEle[index][-1]
 
    # Traverse the matrix and pr
    for i in range(n):
        for j in range(n):
            print (mat[i][j], end = " ")
             
        print()
 
# Driver Code
if __name__ == '__main__':
     
    # Given Matrix mat[][]
    mat = [ [ 1, 2 ],
            [ 4, 5 ] ]
 
    N = len(mat)
 
    # Swap the upper and lower
    # triangular halves
    ReverseSwap(mat, N)
 
# This code is contributed by mohit kumar 29

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to swap laterally inverted
// images of upper and lower triangular
// halves of a given matrix
static void ReverseSwap(int[,] mat, int n)
{
     
    // Store the matrix elements from
    // upper & lower triangular halves
    int[] lowerEle = new int[n];
    int[] upperEle = new int[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 = Math.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] = mat[i, j];
            }
 
            // If current element lies
            // above the principal diagonal
            else
            {
                upperEle[index] = 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 = Math.Abs(i - j);
 
            // Principal diagonal
            if (i == j)
            {
                continue;
            }
 
            // Below main diagonal
            else if (j < i)
            {
                mat[i, j] = upperEle[index];
            }
 
            // Above main diagonal
            else
            {
                mat[i, j] = lowerEle[index--];
            }
        }
    }
 
    // Traverse the matrix and print
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            Console.Write(mat[i, j] + " ");
        }
        Console.WriteLine();
    }
}
 
// Driver Code
static public void Main()
{
     
    // Given Matrix mat[][]
    int[,] mat = new int[,]{ { 1, 2 }, { 4, 5 } };
 
    int N = mat.GetLength(0);
 
    // Swap the upper and lower
    // triangular halves
    ReverseSwap(mat, N);
}
}
 
// This code is contributed by Dharanendra L V

Javascript

<script>
 
// JavaScript program for the above approach
 
// Function to swap laterally inverted
// images of upper and lower triangular
// halves of a given matrix
function  ReverseSwap(mat,n)
{
    // Store the matrix elements from
    // upper & lower triangular halves
    let lowerEle = new Array(n);
    let upperEle = new Array(n);
  
    let index;
  
    // Traverse the matrix mat[][]
    for(let i = 0; i < n; i++)
    {
        for(let j = 0; j < n; j++)
        {
              
            // Find the index
            index = Math.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] = mat[i][j];
            }
  
            // If current element lies
            // above the principal diagonal
            else
            {
                upperEle[index] = mat[i][j];
            }
        }
    }
  
    // Traverse again to swap values
    for(let i = 0; i < n; i++)
    {
        for(let j = 0; j < n; j++)
        {
              
            // Find the index
            index = Math.abs(i - j);
  
            // Principal diagonal
            if (i == j)
            {
                continue;
            }
  
            // Below main diagonal
            else if (j < i)
            {
                mat[i][j] = upperEle[index];
            }
  
            // Above main diagonal
            else
            {
                mat[i][j] = lowerEle[index--];
            }
        }
    }
  
    // Traverse the matrix and print
    for(let i = 0; i < n; i++)
    {
        for(let j = 0; j < n; j++)
        {
            document.write(mat[i][j] + " ");
        }
        document.write("<br>");
    }
}
 
// Driver Code
 
let mat=[[1, 2],[ 4, 5 ]];
let N = mat.length;
// Swap the upper and lower
// triangular halves
ReverseSwap(mat, N);
 
 
// This code is contributed by patel2127
 
</script>
Producción: 

1 4 
2 5

 

Tiempo Complejidad: O(N 2 )
Espacio Auxiliar: O(N 2 )

Publicación traducida automáticamente

Artículo escrito por manupathria y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *