package com.example.lettcode.dailyexercises;
/**
* @Class FlipAndInvertImage
* @Description 832 翻转图像
* 给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。
* 水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。
* 反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。
* <p>
* 示例 1:
* 输入:[[1,1,0],[1,0,1],[0,0,0]]
* 输出:[[1,0,0],[0,1,0],[1,1,1]]
* 解释:首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
* 然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]
* <p>
* 示例 2:
* 输入:[[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
* 输出:[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
* 解释:首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]];
* 然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
* <p>
* 提示:
* 1 <= A.length = A[0].length <= 20
* 0 <= A[i][j] <= 1
* @Author
* @Date 2021/2/24
**/
public class FlipAndInvertImage {
public static int[][] flipAndInvertImage(int[][] A) {
if (A == null || A.length == 0 || A[0].length == 0) return A;
int[][] cloneArray = A.clone();
int row = cloneArray.length;
int col = cloneArray[0].length;
for (int j = 0; j < col / 2; j++) {
for (int i = 0; i < row; i++) {
if (cloneArray[i][j] == 0) cloneArray[i][j] = 1;
else cloneArray[i][j] = 0;
if (cloneArray[i][col - j - 1] == 0) cloneArray[i][col - j - 1] = 1;
else cloneArray[i][col - j - 1] = 0;
cloneArray[i][j] = cloneArray[i][j] + cloneArray[i][col - j - 1];
cloneArray[i][col - j - 1] = cloneArray[i][j] - cloneArray[i][col - j - 1];
cloneArray[i][j] = cloneArray[i][j] - cloneArray[i][col - j - 1];
}
}
if (col % 2 != 0) {
for (int i = 0; i < row; i++) {
if (cloneArray[i][col / 2] == 0) cloneArray[i][col / 2] = 1;
else cloneArray[i][col / 2] = 0;
}
}
return cloneArray;
}
}
// 测试用例
public static void main(String[] args) {
int[][] A = new int[][]{{1, 1, 0}, {1, 0, 1}, {0, 0, 0}};
int[][] ans = FlipAndInvertImage.flipAndInvertImage(A);
System.out.println("FlipAndInvertImage demo01:");
for (int i = 0; i < ans.length; i++) {
System.out.println("");
for (int j = 0; j < ans[0].length; j++) {
System.out.print("," + ans[i][j]);
}
}
System.out.println("");
A = new int[][]{{1, 1, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 1}, {1, 0, 1, 0}};
ans = FlipAndInvertImage.flipAndInvertImage(A);
System.out.println("FlipAndInvertImage demo02:");
for (int i = 0; i < ans.length; i++) {
System.out.println("");
for (int j = 0; j < ans[0].length; j++) {
System.out.print("," + ans[i][j]);
}
}
System.out.println("");
}