Flip an Image / 2 D matrix
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
for (int row = 0; row < A.size(); row++)
{
int numCol = A[row].size();
int col;
for (col = 0; col < (numCol + 1) / 2; col++)
{
int temp = A[row][col] ^ 1;
A[row][col] = A[row][numCol -1 - col] ^ 1;
A[row][numCol - 1 - col] = temp;
}
}
return A;
}
};
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]]
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
for (int row = 0; row < A.size(); row++)
{
int numCol = A[row].size();
int col;
for (col = 0; col < (numCol + 1) / 2; col++)
{
int temp = A[row][col] ^ 1;
A[row][col] = A[row][numCol -1 - col] ^ 1;
A[row][numCol - 1 - col] = temp;
}
}
return A;
}
};
No comments:
Post a Comment