DEV Community

Cover image for Flipping an Image(leetcode)
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

Flipping an Image(leetcode)

INTRODUCTION

Image description

Our problem says, we are given an 2D array. At first we have to reverse each row of the array, then we have to invert(if 0 then set 1, if the value is 1 then set 0) all the elements of the array.

Examples

Image description

Steps

  1. Take a for loop.
  2. reverse each row using while loop.
  3. After reversing now traverse the row again and invert the value.
  4. In the end return the array.

JavaCode

class Solution {
    public int[][] flipAndInvertImage(int[][] image) {
        for(int i = 0; i<image.length; i++){
            int temp = 0, j = 0, k= image[i].length-1;
            while(j < k){
                temp = image[i][j];
                image[i][j] = image[i][k];
                image[i][k] = temp;
                j++;
                k--;
            }

            for(int l = 0; l<image[i].length; l++){
                if(image[i][l] == 1){
                    image[i][l] = 0;
                }else{
                    image[i][l] = 1;
                }
            }
        }
        return image;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)