Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.
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].
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].
Example 1:
Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
Example 2:
Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
原文链接:https://leetcode.com/problems/flipping-an-image/
题目要求将一个矩阵进行变换,先将其的子数组进行逆向,比如[1,1,0],将其逆向为[0,1,1]。然后再将逆向的数组中的所有元素分别进行转换,将1变成0,0变成1,也就是对1进行异或操作。
可以通过观察发现,经过这两次操作之后,对原来的数组来说发生了如下变化:
[1,1,0,0] —> [0,0,1,1] —> [1,1,0,0]
[1,0,0,1] —> [1,0,0,1] —> [0,1,1,0]
[0,1,1,1] —> [1,1,1,0] —> [0,0,0,1]
[1,1,0] —> [0,1,1] —> [1,0,0]
[1,0,1] —> [1,0,1] —> [0,1,0]
可以通过观察发现,由于经过了逆向和与1异或,最初的数组和最终的数组差别:如果前面位置上为0则对称后面位置则设置为1,如果前面为1则对称后面位置上设置为0。后面位置也是这样的规则。
不难写出如下代码:
/*class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
if(A.size()==0 || A[0].size()==0)
return A;
int p1,p2;
int i=0,temp;
while(i < A.size()) {
p1=0,p2=A[0].size()-1;// 分别从两端向中间进行扫描
while(p1 <= p2) {
temp = A[i][p1];// 记录下前面位置上的数字
A[i][p1] = 1-A[i][p2];//如果对应后面位置为0,则将前面设置为1,否则设置为0
A[i][p2] = 1-temp;//前面为0,后面设置为1,反之为0.
p1++;
p2--;
if(p1 == p2) {//只剩下中间的一个数字
A[i][p1] = 1-A[i][p1];
break;
}
}
i++;
}
return A;
}
};*/
再次观察可以发现,如果对称位置上数字不相同的话(一个为0另一个为1),经过变化之后还和原来一样,这种情况下对应位置是不变的。但是如果对称位置上数字相同的话,经过变换之后就相当于与1进行异或操作,所以可以得出如下代码。
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
for (int i = 0; i < A.size(); ++i){
int begin = 0;
int end = A[0].size()-1;
while (begin < end){
if(A[i][begin] == A[i][end]){// 如果前面和后面相等,此时需要进行对1进行异或,
A[i][begin] ^= 0X1;
A[i][end] ^= 0X1;
}
++begin;
--end;
}
if(begin == end) A[i][begin] ^=1;
}
return A;
}
};