Flipping an Image

Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed.  For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].

Example 1:

Input: {{1,1,0},{1,0,1},{0,0,0}}
Output: [[1,0,0],[0,1,0],[1,1,1]]

Approach

Java

import java.util.Arrays;

public class FlippingAnImage {
    public static void main(String[] args) {
        int A[][] = { { 110 }, { 101 }, { 000 } };
        int res[][] = flipAndInvertImage(A);
        System.out.println(Arrays.deepToString(res));
    }

    static int[][] flipAndInvertImage(int[][] A) {
        for (int i = 0; i < A.length; i++) {
            // reverse the array and reassign
            A[i] = reverseArray(A[i]);
        }

        for (int i = 0; i < A.length; i++) {
            A[i] = Arrays.stream(A[i]).map(j -> j == 1 ? 0 : 1).toArray();
        }
        return A;
    }

    // reverse the array
    private static int[] reverseArray(int[] a) {
        int temp;
        int size = a.length;
        for (int i = 0; i < size / 2; i++) {
            temp = a[i];
            a[i] = a[size - i - 1];
            a[size - i - 1] = temp;
        }
        return a;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;


vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A
{
      for(int i=0;i<A.size();i++)
            reverse(A[i].begin(),A[i].end());
        for(int i=0;i<A.size();i++)
        {
            for(int j=0;j<A[i].size();j++)
                   A[i][j]=!A[i][j];
        }
     return A;
}
int main()
{
    vector<vector<int>> A={{1,1,0},{1,0,1},{0,0,0}};
    A=flipAndInvertImage(A);
  cout<<"[";
    for(int i=0;i<A.size();i++)
       {
           cout<<"[";
           for(int j=0;j<A[0].size();j++)
             {
               cout<<A[i][j];
               if(j!=A[0].size()-1)
                   cout<<",";   
             }
             cout<<"]";
            if(i!=A.size()-1)
              cout<<",";
       }
    cout<<"]";
}



No comments:

Post a Comment