Skip to content

Commit f6f4d72

Browse files
authored
Create 0832. Flipping an Image
1 parent 99b6e63 commit f6f4d72

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

0832. Flipping an Image

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/****************************************
2+
832. Flipping an Image
3+
4+
Difficulty: Easy
5+
6+
Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.
7+
8+
To flip an image horizontally means that each row of the image is reversed.
9+
For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
10+
11+
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
12+
For example, inverting [0, 1, 1] results in [1, 0, 0].
13+
14+
Example 1:
15+
Input: [[1,1,0],[1,0,1],[0,0,0]]
16+
Output: [[1,0,0],[0,1,0],[1,1,1]]
17+
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
18+
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
19+
20+
Example 2:
21+
Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
22+
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
23+
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
24+
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
25+
26+
Notes:
27+
1 <= A.length = A[0].length <= 20
28+
0 <= A[i][j] <= 1
29+
30+
****************************************/
31+
32+
33+
class Solution {
34+
public int[][] flipAndInvertImage(int[][] A) {
35+
return invertImage(flipImage(A));
36+
}
37+
38+
public int[][] invertImage(int[][] A) {
39+
for(int i = 0; i < A.length; i++) {
40+
for(int j = 0; j < A[i].length; j++) {
41+
if (A[i][j] == 1) {
42+
A[i][j] = 0;
43+
}
44+
else {
45+
A[i][j] = 1;
46+
}
47+
}
48+
}
49+
return A;
50+
}
51+
52+
public int[][] flipImage(int[][] A){
53+
for(int i = 0; i < A.length; i++) {
54+
for(int j = 0; j < A[i].length / 2; j++) {
55+
int temp = A[i][j];
56+
A[i][j] = A[i][A.length - 1 - j];
57+
A[i][A.length - 1 - j] = temp;
58+
}
59+
}
60+
return A;
61+
}
62+
}

0 commit comments

Comments
 (0)