给定一个二进制矩阵 A
,我们想先水平翻转图像,然后反转图像并返回结果。
水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0]
的结果是 [0, 1, 1]
。
反转图片的意思是图片中的 0
全部被 1
替换, 1
全部被 0
替换。例如,反转 [0, 1, 1]
的结果是 [1, 0, 0]
。
示例 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]]
示例 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]]
提示:
1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1
遍历矩阵每一行,利用双指针 p, q 进行水平交换翻转,顺便反转图像(1 变 0,0 变 1:1 ^ 1
= 0,0 ^ 1
= 1)。
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
m, n = len(A), len(A[0])
for i in range(m):
p, q = 0, n - 1
while p < q:
t = A[i][p] ^ 1
A[i][p] = A[i][q] ^ 1
A[i][q] = t
p += 1
q -= 1
if p == q:
A[i][p] ^= 1
return A
class Solution {
public int[][] flipAndInvertImage(int[][] A) {
int m = A.length, n = A[0].length;
for (int i = 0; i < m; ++i) {
int p = 0, q = n - 1;
while (p < q) {
int t = A[i][p] ^ 1;
A[i][p] = A[i][q] ^ 1;
A[i][q] = t;
++p;
--q;
}
if (p == q) {
A[i][p] ^= 1;
}
}
return A;
}
}
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
int m = A.size(), n = A[0].size();
for (int i = 0; i < m; ++i) {
int p = 0, q = n - 1;
while (p < q) {
int t = A[i][p] ^ 1;
A[i][p] = A[i][q] ^ 1;
A[i][q] = t;
++p;
--q;
}
if (p == q) {
A[i][p] ^= 1;
}
}
return A;
}
};