Flipping an Image(leetcode)
Tahzib Mahmud Rifat

Tahzib Mahmud Rifat @rifat87

About: Open source || Backend-Development || IoT || Robotics || Computer Vision

Joined:
Feb 13, 2024

Flipping an Image(leetcode)

Publish Date: Mar 29 '24
0 0

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

Comments 0 total

    Add comment