832. Flipping an Image

2022. 8. 21. 22:52STUDY/LeetCode

반응형

Given an n x n binary matrix image, 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: image = [[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: image = [[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]]

Constraints:

  • n == image.length
  • n == image[i].length
  • 1 <= n <= 20
  • images[i][j] is either 0 or 1.

 

# 풀이 

2차 배열 푼 김에 Matrix 문제좀 풀어볼라고 햇더니 ... 왜 이 쉬운게 생각이 안난거야.. 

1. reverse

2. XOR 

해주면 된다. 

 

# 정답

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
#if 0
vector<vector<int> > flipAndInvertImage(vector<vector<int> >& image) {
 
    for(auto& row : image) {
        reverse(row.begin(), row.end());
        for(auto& v : row) v ^= 1;
    }
    return image;
}
#else
vector<vector<int> > flipAndInvertImage(vector<vector<int> > & image) {
    for(int i = 0; i < image.size(); i++) {
        reverse(image[i].begin(), image[i].end());
        for(int j = 0; j < image.size(); j++) {
            image[i][j] ^= 0x1;
        }
    }
    return image;
}
#endif
 
int main()
{
 
    //vector<vector<int> > vv{
    //{1,1,0}, {1,0,1}, {0,0,0}
    //};
 
    vector<vector<int> > vv {
    {1,1,0,0}, {1,0,0,1}, {0,1,1,1}, {1,0,1,0}
    };
    
    //cout << vv.size() << ' ' << vv[0].size() << '\n';
    
    flipAndInvertImage(vv);
    for(int i = 0; i < vv.size(); i++) { // 행
        for (int j = 0; j < vv[0].size(); j++) { // 열 
            cout << vv[i][j] << ' ';
        }
        cout << '\n';
    }
    
    return 0;
}
cs

 

음 그래 vector의 행 값 열 값은 그냥 써줘도 되지.. ! 

728x90
반응형