https://leetcode-cn.com/problems/flipping-an-image/
给定一个二进制矩阵 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
按照题目说的来呗,先翻转,后反转
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
flip(A);
Invert(A);
return A;
}
private:
void flip(vector<vector<int>>& A){
int row = A.size();
int col = A[0].size();
int n = col / 2;
for(int i=0; i<row; i++){
for(int j=0; j<n; j++){
swap(A[i][j], A[i][col-1-j]);
}
}
}
void Invert(vector<vector<int>>& A){
int row = A.size();
int col = A[0].size();
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
A[i][j] == 1 ? A[i][j] = 0 : A[i][j] = 1;
}
}
}
};