Gire todos los elementos de Matrix excepto la diagonal K veces 90 grados en el sentido de las agujas del reloj

Dada una array cuadrada mat[][] de dimensión N y un número entero K , la tarea es rotar la array 90 grados K ​​veces sin cambiar la posición de los elementos diagonales.

Ejemplos:

Entrada: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1
Salida:
 1 16 11 6 5  
 22 7 12 9 2
 23 18 13 8 3
 24 17 14 19 4
 21 20 15 10 25

Entrada: mat[][] = {{10, 11}, {12, 13}}, K = 2
Salida:
10 11
12 13

Enfoque: El problema dado se puede resolver usando la idea discutida en este artículo y el hecho de que la array se restaura después de realizar una rotación en el sentido de las agujas del reloj 4 veces. Siga los pasos a continuación para resolver el problema dado:

  • Actualice el valor de K como K % 4 .
  • Iterar hasta que K sea positivo y realizar los siguientes pasos:
    • Recorra la array , para i sobre el rango [0, N / 2) y j sobre el rango [0, N – i – 1) y realice los siguientes pasos:
    • Si el valor de i != j y (i + j) != (N – 1) , realice los siguientes pasos:
      • Almacene el valor de mat[i][j] en una variable temporal temp .
      • Actualice el valor de mat[i][j] como mat[N – 1 – j][i] .
      • Actualice el valor de mat[N – 1 – j][i] como mat[N – 1 -i][N – 1 – j] .
      • Actualice el valor de mat[N – 1 – i][N – 1 – j] como mat[j][N – 1 – i] .
      • Actualice el valor de mat[j][N – 1 – i] como temp .
  • Después de completar los pasos anteriores, imprima la array actualizada obtenida.

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 print the matrix
void print(vector<vector<int> >& mat)
{
    // Iterate over the rows
    for (int i = 0; i < mat.size(); i++) {
 
        // Iterate over the columns
        for (int j = 0; j < mat[0].size(); j++)
 
            // Print the value
            cout << setw(3) << mat[i][j];
        cout << "\n";
    }
}
 
// Function to perform the swapping of
// matrix elements in clockwise manner
void performSwap(vector<vector<int> >& mat,
                 int i, int j)
{
    int N = mat.size();
 
    // Stores the last row
    int ei = N - 1 - i;
 
    // Stores the last column
    int ej = N - 1 - j;
 
    // Perform the swaps
    int temp = mat[i][j];
    mat[i][j] = mat[ej][i];
    mat[ej][i] = mat[ei][ej];
    mat[ei][ej] = mat[j][ei];
    mat[j][ei] = temp;
}
 
// Function to rotate non - diagonal
// elements of the matrix K times in
// clockwise direction
void rotate(vector<vector<int> >& mat,
            int N, int K)
{
    // Update K to K % 4
    K = K % 4;
 
    // Iterate until K is positive
    while (K--) {
 
        // Iterate each up to N/2-th row
        for (int i = 0; i < N / 2; i++) {
 
            // Iterate each column
            // from i to N - i - 1
            for (int j = i;
                 j < N - i - 1; j++) {
 
                // Check if the element
                // at i, j is not a
                // diagonal element
                if (i != j
                    && (i + j) != N - 1) {
 
                    // Perform the swapping
                    performSwap(mat, i, j);
                }
            }
        }
    }
 
    // Print the matrix
    print(mat);
}
 
// Driver Code
int main()
{
    int K = 5;
    vector<vector<int> > mat = {
        { 1, 2, 3, 4 },
        { 6, 7, 8, 9 },
        { 11, 12, 13, 14 },
        { 16, 17, 18, 19 },
    };
    int N = mat.size();
    rotate(mat, N, K);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
public class GFG {
 
    // Function to print the matrix
    static void print(int mat[][])
    {
        // Iterate over the rows
        for (int i = 0; i < mat.length; i++) {
 
            // Iterate over the columns
            for (int j = 0; j < mat[0].length; j++)
 
                // Print the value
                System.out.print(mat[i][j] + " ");
           
            System.out.println();
        }
    }
 
    // Function to perform the swapping of
    // matrix elements in clockwise manner
    static void performSwap(int mat[][], int i, int j)
    {
        int N = mat.length;
 
        // Stores the last row
        int ei = N - 1 - i;
 
        // Stores the last column
        int ej = N - 1 - j;
 
        // Perform the swaps
        int temp = mat[i][j];
        mat[i][j] = mat[ej][i];
        mat[ej][i] = mat[ei][ej];
        mat[ei][ej] = mat[j][ei];
        mat[j][ei] = temp;
    }
 
    // Function to rotate non - diagonal
    // elements of the matrix K times in
    // clockwise direction
    static void rotate(int mat[][], int N, int K)
    {
        // Update K to K % 4
        K = K % 4;
 
        // Iterate until K is positive
        while (K-- > 0) {
 
            // Iterate each up to N/2-th row
            for (int i = 0; i < N / 2; i++) {
 
                // Iterate each column
                // from i to N - i - 1
                for (int j = i; j < N - i - 1; j++) {
 
                    // Check if the element
                    // at i, j is not a
                    // diagonal element
                    if (i != j && (i + j) != N - 1) {
 
                        // Perform the swapping
                        performSwap(mat, i, j);
                    }
                }
            }
        }
 
        // Print the matrix
        print(mat);
    }
   
    // Driver Code
    public static void main(String[] args)
    {
 
        int K = 5;
        int mat[][] = {
            { 1, 2, 3, 4 },
            { 6, 7, 8, 9 },
            { 11, 12, 13, 14 },
            { 16, 17, 18, 19 },
        };
       
        int N = mat.length;
        rotate(mat, N, K);
    }
}
 
// This code is contributed by Kingash.

Python3

# Python3 program for the above approach
 
# Function to print the matrix
def printMat(mat):
   
    # Iterate over the rows
    for i in range(len(mat)):
 
        # Iterate over the columns
        for j in range(len(mat[0])):
 
            # Print the value
            print(mat[i][j], end = " ")
             
        print()
 
# Function to perform the swapping of
# matrix elements in clockwise manner
def performSwap(mat, i, j):
   
    N = len(mat)
 
    # Stores the last row
    ei = N - 1 - i
 
    # Stores the last column
    ej = N - 1 - j
 
    # Perform the swaps
    temp = mat[i][j]
    mat[i][j] = mat[ej][i]
    mat[ej][i] = mat[ei][ej]
    mat[ei][ej] = mat[j][ei]
    mat[j][ei] = temp
 
# Function to rotate non - diagonal
# elements of the matrix K times in
# clockwise direction
def rotate(mat, N, K):
 
    # Update K to K % 4
    K = K % 4
 
    # Iterate until K is positive
    while (K > 0):
 
        # Iterate each up to N/2-th row
        for i in range(int(N / 2)):
 
            # Iterate each column
            # from i to N - i - 1
            for j in range(i, N - i - 1):
 
                # Check if the element
                # at i, j is not a
                # diagonal element
                if (i != j and (i + j) != N - 1):
 
                    # Perform the swapping
                    performSwap(mat, i, j)
                     
        K -= 1
                     
    # Print the matrix
    printMat(mat)
 
# Driver Code
K = 5
mat = [ [ 1, 2, 3, 4 ],
        [ 6, 7, 8, 9 ],
        [ 11, 12, 13, 14 ],
        [ 16, 17, 18, 19 ] ]
N = len(mat)
 
rotate(mat, N, K)
 
# This code is contributed by Dharanendra L V.

C#

// C# program for the above approach
using System;
public class GFG {
 
    // Function to print the matrix
    static void print(int[, ] mat)
    {
        // Iterate over the rows
        for (int i = 0; i < mat.GetLength(0); i++) {
 
            // Iterate over the columns
            for (int j = 0; j < mat.GetLength(1); j++)
 
                // Print the value
                Console.Write(mat[i, j] + " ");
 
            Console.WriteLine();
        }
    }
 
    // Function to perform the swapping of
    // matrix elements in clockwise manner
    static void performSwap(int[, ] mat, int i, int j)
    {
        int N = mat.GetLength(0);
 
        // Stores the last row
        int ei = N - 1 - i;
 
        // Stores the last column
        int ej = N - 1 - j;
 
        // Perform the swaps
        int temp = mat[i, j];
        mat[i, j] = mat[ej, i];
        mat[ej, i] = mat[ei, ej];
        mat[ei, ej] = mat[j, ei];
        mat[j, ei] = temp;
    }
 
    // Function to rotate non - diagonal
    // elements of the matrix K times in
    // clockwise direction
    static void rotate(int[, ] mat, int N, int K)
    {
        // Update K to K % 4
        K = K % 4;
 
        // Iterate until K is positive
        while (K-- > 0) {
 
            // Iterate each up to N/2-th row
            for (int i = 0; i < N / 2; i++) {
 
                // Iterate each column
                // from i to N - i - 1
                for (int j = i; j < N - i - 1; j++) {
 
                    // Check if the element
                    // at i, j is not a
                    // diagonal element
                    if (i != j && (i + j) != N - 1) {
 
                        // Perform the swapping
                        performSwap(mat, i, j);
                    }
                }
            }
        }
 
        // Print the matrix
        print(mat);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
 
        int K = 5;
        int[, ] mat = {
            { 1, 2, 3, 4 },
            { 6, 7, 8, 9 },
            { 11, 12, 13, 14 },
            { 16, 17, 18, 19 },
        };
 
        int N = mat.GetLength(0);
        rotate(mat, N, K);
    }
}
 
// This code is contributed by ukasp.

Javascript

<script>
 
// Javascript implementation of the above approach
 
   // Function to print the matrix
    function print(mat)
    {
        // Iterate over the rows
        for (let i = 0; i < mat.length; i++) {
  
            // Iterate over the columns
            for (let j = 0; j < mat[0].length; j++)
  
                // Print the value
                document.write(mat[i][j] + " ");
            
            document.write("<br/>");
        }
    }
  
    // Function to perform the swapping of
    // matrix elements in clockwise manner
    function performSwap(mat, i, j)
    {
        let N = mat.length;
  
        // Stores the last row
        let ei = N - 1 - i;
  
        // Stores the last column
        let ej = N - 1 - j;
  
        // Perform the swaps
        let temp = mat[i][j];
        mat[i][j] = mat[ej][i];
        mat[ej][i] = mat[ei][ej];
        mat[ei][ej] = mat[j][ei];
        mat[j][ei] = temp;
    }
  
    // Function to rotate non - diagonal
    // elements of the matrix K times in
    // clockwise direction
    function rotate(mat, N, K)
    {
        // Update K to K % 4
        K = K % 4;
  
        // Iterate until K is positive
        while (K-- > 0) {
  
            // Iterate each up to N/2-th row
            for (let i = 0; i < N / 2; i++) {
  
                // Iterate each column
                // from i to N - i - 1
                for (let j = i; j < N - i - 1; j++) {
  
                    // Check if the element
                    // at i, j is not a
                    // diagonal element
                    if (i != j && (i + j) != N - 1) {
  
                        // Perform the swapping
                        performSwap(mat, i, j);
                    }
                }
            }
        }
  
        // Print the matrix
        print(mat);
    }
 
  // Driver Code
     
     let K = 5;
        let mat = [
            [ 1, 2, 3, 4 ],
            [ 6, 7, 8, 9 ],
            [ 11, 12, 13, 14 ],
            [ 16, 17, 18, 19 ],
        ];
        
        let N = mat.length;
        rotate(mat, N, K);
       
</script>
Producción: 

  1 11  6  4
 17  7  8  2
 18 12 13  3
 16 14  9 19

 

Complejidad Temporal: O(N 2 )
Espacio Auxiliar: O(1), ya que no se ha tomado ningún espacio extra.

Publicación traducida automáticamente

Artículo escrito por rahulagarwal14 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 *