|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 832. Flipping an Image |
| 5 | + * |
| 6 | + * Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. |
| 7 | + * 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]. |
| 8 | + * 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]. |
| 9 | + * |
| 10 | + * Example 1: |
| 11 | + * Input: [[1,1,0],[1,0,1],[0,0,0]] |
| 12 | + * Output: [[1,0,0],[0,1,0],[1,1,1]] |
| 13 | + * Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. |
| 14 | + * Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] |
| 15 | + * |
| 16 | + * Example 2: |
| 17 | + * Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] |
| 18 | + * Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] |
| 19 | + * Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. |
| 20 | + * Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] |
| 21 | + * |
| 22 | + * Notes: |
| 23 | + * 1 <= A.length = A[0].length <= 20 |
| 24 | + * 0 <= A[i][j] <= 1 |
| 25 | + */ |
| 26 | +public class _832 { |
| 27 | + public static class Solution1 { |
| 28 | + public int[][] flipAndInvertImage(int[][] A) { |
| 29 | + int m = A.length; |
| 30 | + int n = A[0].length; |
| 31 | + int[][] result = new int[m][n]; |
| 32 | + for (int i = 0; i < m; i++) { |
| 33 | + int[] flipped = (reverse(A[i])); |
| 34 | + result[i] = invert(flipped); |
| 35 | + } |
| 36 | + return result; |
| 37 | + } |
| 38 | + |
| 39 | + private int[] invert(int[] flipped) { |
| 40 | + int[] result = new int[flipped.length]; |
| 41 | + for (int i = 0; i < flipped.length; i++) { |
| 42 | + if (flipped[i] == 0) { |
| 43 | + result[i] = 1; |
| 44 | + } else { |
| 45 | + result[i] = 0; |
| 46 | + } |
| 47 | + } |
| 48 | + return result; |
| 49 | + } |
| 50 | + |
| 51 | + private int[] reverse(int[] nums) { |
| 52 | + for (int i = 0, j = nums.length - 1; i < j; i++, j--) { |
| 53 | + int tmp = nums[i]; |
| 54 | + nums[i] = nums[j]; |
| 55 | + nums[j] = tmp; |
| 56 | + } |
| 57 | + return nums; |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments