Voltear horizontalmente una array binaria

Dada una array binaria. La tarea es voltear la array horizontalmente (encontrar la imagen de la array) y luego invertirla. 

Nota

  • Voltear una array horizontalmente significa invertir cada fila de la array. Por ejemplo, voltear [1, 1, 0, 0] horizontalmente da como resultado [0, 0, 1, 1].
  • Invertir una array significa reemplazar cada 0 por 1 y viceversa. Por ejemplo, invertir [0, 0, 1] da como resultado [1, 1, 0].

Ejemplos

Input: mat[][] = [[1, 1, 0], 
                  [1, 0, 1], 
                  [0, 0, 0]]
Output: [[1, 0, 0], 
         [0, 1, 0], 
         [1, 1, 1]]
Explanation: 
First reverse each row: [[0, 1, 1], [1, 0, 1], [0, 0, 0]]
Then, invert the image: [[1, 0, 0], [0, 1, 0], [1, 1, 1]]
Input: mat[][] = [[1, 1, 0, 0], 
                  [1, 0, 0, 1], 
                  [0, 1, 1, 1], 
                  [1, 0, 1, 0]]
Output: [[1, 1, 0, 0], 
         [0, 1, 1, 0], 
         [0, 0, 0, 1], 
         [1, 0, 1, 0]]
Explanation: 
First reverse each row: 
[[0, 0, 1, 1], [1, 0, 0, 1], [1, 1, 1, 0], [0, 1, 0, 1]].
Then invert the image:
[[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]]

Enfoque: Podemos hacer esto en el lugar. Observando detenidamente, se puede deducir que en cada fila de la array final, el i-ésimo valor de la izquierda es igual a la inversa del i-ésimo valor de la derecha de la array binaria de entrada. Por lo tanto, usamos (Columna + 1) / 2 (con división de piso) para iterar sobre todos los índices  i                   en la primera mitad de la fila, incluido el centro y actualizar la respuesta en consecuencia.

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

Java

// java implementation of above approach
// Function to return final Image
import java.io.*;
import java.util.Arrays;
class GFG {
  public static void main(String[] args)
  {
 
    // Driver code
    int[][] mat = { { 1, 1, 0, 0 },
                   { 1, 0, 0, 1 },
                   { 0, 1, 1, 1 },
                   { 1, 0, 1, 0 } };
 
    int[][] matrix = flipped_Invert_Image(mat);
    for (int[] matele : matrix) {
      System.out.print(Arrays.toString(matele));
    }
  }
 
  public static int[][] flipped_Invert_Image(int[][] mat)
  {
    for (int[] row : mat) {
      for (int i = 0; i < (mat[0].length + 1) / 2; i++)
      {
        // swap
        int temp = row[i] ^ 1;
        row[i] = row[mat[0].length - 1 - i] ^ 1;
        row[mat[0].length - 1 - i] = temp;
      }
    }
 
    // return Flipped and Inverted image
    return mat;
  }
}
 
// This code is contributed by devendra salunke

Python3

# Python3 implementation of above approach
# Function to return final Image
 
def flipped_Invert_Image(mat):
 
    for row in mat:
        for i in range((len(row) + 1) // 2):
 
            row[i] = row[len(row) - 1 - i] ^ 1
            row[len(row) - 1 - i] = row[i] ^ 1
 
    # return Flipped and Inverted image
    return mat
 
# Driver code
mat = [[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]]
 
print(flipped_Invert_Image(mat))

C#

// C# implementation of above approach
// Function to return final Image
using System;
using System.Collections.Generic;
 
public class GFG {
  public static int[, ] flipped_Invert_Image(int[, ] mat)
  {
    for (int j = 0; j < mat.GetLength(0); j++) {
      for (int i = 0; i < (mat.GetLength(1) + 1) / 2;
           i++) {
        // swap
        int temp = mat[j, i] ^ 1;
        mat[j, i]
          = mat[j, mat.GetLength(1) - 1 - i] ^ 1;
        mat[j, mat.GetLength(1) - 1 - i] = temp;
      }
    }
 
    return mat;
  }
 
  public static void Main(string[] args)
  {
 
    // Driver code
    int[, ] mat = { { 1, 1, 0, 0 },
                   { 1, 0, 0, 1 },
                   { 0, 1, 1, 1 },
                   { 1, 0, 1, 0 } };
 
    int[, ] matrix = flipped_Invert_Image(mat);
 
 
    //Printing the formatted array     
    Console.Write("[");
    for (int j = 0; j < matrix.GetLength(0); j++) {
      Console.Write("[");
      for (int i = 0; i < matrix.GetLength(1); i++) {
        Console.Write(matrix[j, i]);
 
        if (i != matrix.GetLength(1) - 1)
          Console.Write(", ");
      }
      Console.Write("]");
      if (j != matrix.GetLength(0) - 1)
        Console.Write(", ");
    }
    Console.Write("]");
  }
}
 
// This code is contributed by phasing17

Javascript

<script>
 
// JavaScript implementation of above approach
// Function to return final Image
 
function flipped_Invert_Image(mat){
 
    for(let row of mat){
        for(let i=0;i<Math.floor((row.length + 1) / 2);i++){
 
            row[i] = row[row.length - 1 - i] ^ 1
            row[row.length - 1 - i] = row[i] ^ 1
        }
    }
 
    // return Flipped and Inverted image
    return mat
}
 
 
// Driver code
let mat = [[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]]
 
document.write(flipped_Invert_Image(mat))
 
// This code is contributed by shinjanpatra
 
</script>
Producción: 

[[1, 1, 0, 0], [0, 1, 0, 1], [0, 0, 1, 1], [1, 0, 1, 0]]

 

Complejidad de tiempo: O(N*M), donde N es el número de filas y M es el número de columnas en la array binaria dada.

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

Java

// Java  program to flip the binary image horizontally
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int[][] matrix
            = { { 1, 1, 0 }, { 1, 0, 1 }, { 0, 0, 0 } };
        int[][] v = flip_matrix(matrix);
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(v[i][j] + " ");
            }
            System.out.println();
        }
    }
 
    // function to flip the matrix using two pointer
    // technique
    public static int[][] flip_matrix(int[][] matrix)
    {
        for (int i = 0; i < matrix.length; i++) {
            int left = 0;
            int right = matrix[i].length - 1;
 
            while (left <= right) {
                // conditions executes if compared elements
                // are not equal
                if (matrix[i][left] == matrix[i][right]) {
                    // if element is 0 it becomes 1 if not
                    // it becomes 0
                    matrix[i][left] = 1 - matrix[i][left];
                    matrix[i][right] = matrix[i][left];
                }
                left++;
                right--;
            }
        }
        // return matrix
        return matrix;
    }
}
// This code is contributed by devendra salunke

C++14

//c++ program to flip the binary image horizontally
#include<bits/stdc++.h>
using namespace std;
//function to flip the matrix using two pointer technique
vector<vector<int>> flip_matrix(vector<vector<int>>matrix)
{
    for(int i=0;i<matrix.size();i++)
         { 
             int left = 0;
             int right = matrix[i].size()-1;
              
             while( left <= right )
             {
                 //conditions executes if compared elements are not equal
                 if(matrix[i][left] == matrix[i][right])
                 {
                     // if element is 0 it becomes 1 if not it becomes 0
                     matrix[i][left] = 1-matrix[i][left];
                     matrix[i][right] = matrix[i][left];
                 }
                 left++;
                 right--;
             }
         }
         //return matrix
        return matrix;
}
//Drive code
int main()
{
    vector<vector<int>>matrix={{1,1,0},{1,0,1},{0,0,0}};
    vector<vector<int>>v=flip_matrix(matrix);
    for(int i=0;i<matrix.size();i++)
    {
        for(int j=0;j<matrix[i].size();j++)
        {
            cout<<v[i][j]<<" ";
        }
        cout<<'\n';
    }
}

Python3

# Python program to flip the binary image horizontally
 
# function to flip the matrix using two pointer technique
def flip_matrix(matrix):
 
    for i in range(len(matrix)):
        left,right = 0,len(matrix[i])-1
             
        while(left <= right):
           
            # conditions executes if compared elements are not equal
            if(matrix[i][left] == matrix[i][right]):
               
                #  if element is 0 it becomes 1 if not it becomes 0
                matrix[i][left] = 1-matrix[i][left]
                matrix[i][right] = matrix[i][left]
                 
            left += 1
            right -= 1
         
    # return matrix
    return matrix
 
# Drive code
matrix = [[1, 1, 0], [1, 0, 1], [0, 0, 0]]
v = flip_matrix(matrix)
 
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
       print(v[i][j],end = " ")
    print()
 
# This code is contributed by shinjanpatra

C#

// C#  program to flip the binary image horizontally
 
using System;
 
class GFG {
 
    // Driver code
    public static void Main(string[] args)
    {
        int[][] matrix
            = { new[] { 1, 1, 0 }, new[] { 1, 0, 1 },
                new[] { 0, 0, 0 } };
        int[][] v = flip_matrix(matrix);
        for (int i = 0; i < matrix.Length; i++) {
            for (int j = 0; j < matrix[i].Length; j++) {
                Console.Write(v[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
 
    // function to flip the matrix using two pointer
    // technique
    public static int[][] flip_matrix(int[][] matrix)
    {
        for (int i = 0; i < matrix.Length; i++) {
            int left = 0;
            int right = matrix[i].Length - 1;
 
            while (left <= right) {
                // conditions executes if compared elements
                // are not equal
                if (matrix[i][left] == matrix[i][right]) {
                    // if element is 0 it becomes 1 if not
                    // it becomes 0
                    matrix[i][left] = 1 - matrix[i][left];
                    matrix[i][right] = matrix[i][left];
                }
                left++;
                right--;
            }
        }
        // return matrix
        return matrix;
    }
}
// This code is contributed by devendra salunke

Javascript

<script>
 
// JavaScript implementation of above approach
 
// function to flip the matrix using two pointer technique
function flip_matrix(matrix)
{
    for(let i = 0; i < matrix.length; i++)
         { 
             let left = 0;
             let right = matrix[i].length-1;
              
             while( left <= right )
             {
                 // conditions executes if compared elements are not equal
                 if(matrix[i][left] == matrix[i][right])
                 {
                     // if element is 0 it becomes 1 if not it becomes 0
                     matrix[i][left] = 1-matrix[i][left];
                     matrix[i][right] = matrix[i][left];
                 }
                 left++;
                 right--;
             }
         }
         // return matrix
        return matrix;
}
 
// Drive code
let matrix = [[1,1,0],[1,0,1],[0,0,0]];
let v = flip_matrix(matrix);
 
for(let i = 0 ; i < matrix.length; i++)
{
    for(let j = 0; j < matrix[i].length; j++)
    {
        document.write(v[i][j]," ");
    }
    document.write("</br>");
}
 
// This code is contributed by shinjanpatra
 
</script>
Producción

1 0 0 
0 1 0 
1 1 1 

Complejidad temporal: O(N*M) donde N y M son las dimensiones de la array. Espacio auxiliar: O(1)

Publicación traducida automáticamente

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