-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotate2D.java
More file actions
99 lines (80 loc) · 2.46 KB
/
Copy pathRotate2D.java
File metadata and controls
99 lines (80 loc) · 2.46 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* You are given an n x n 2D matrix representing an image.
*
Rotate the image by 90 degrees (clockwise).
You need to do this in place.
Note that if you end up using an additional array, you will only receive partial score.
Example:
If the array is
[
[1, 2],
[3, 4]
]
Then the rotated array becomes:
[
[3, 1],
[4, 2]
]
http://www.programcreek.com/2013/01/leetcode-rotate-image-java/
*/
import java.util.*;
public class Rotate2D{
public static void rotate(ArrayList<ArrayList<Integer>> A) {
if(A == null)
return;
int n = A.size();
if(n == 0)
return;
int layers = n;
int row1, col1, row2, col2;
int num;
int temp;
int first, last;
for(int layer = 0; layer < layers/2; layer++){
first = layer;
last = n - layer - 1;
for(int i = first; i < last; i++){
int offset = i-layer;
int top = A.get(first).get(i);
A.get(first).set(i, A.get(last-offset).get(first)); // topleft = bottomleft
A.get(last-offset).set(first, A.get(last).get(last-offset));//bottomleft = bottomright
A.get(last).set(last-offset, A.get(i).get(last));//bottomright = topright;
A.get(i).set(last, top);
}
}
System.out.println();
for(ArrayList<Integer> t : A)
System.out.println(t);
}
public static void main(String[] args){
ArrayList<ArrayList<Integer>> A = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(1);
temp.add(2);
temp.add(3);
temp.add(4);
A.add(new ArrayList<Integer>(temp));
temp.clear();
temp.add(5);
temp.add(6);
temp.add(7);
temp.add(8);
A.add(new ArrayList<Integer>(temp));
temp.clear();
temp.add(9);
temp.add(10);
temp.add(11);
temp.add(12);
A.add(new ArrayList<Integer>(temp));
temp.clear();
temp.add(13);
temp.add(14);
temp.add(15);
temp.add(16);
A.add(new ArrayList<Integer>(temp));
temp.clear();
for(ArrayList<Integer> t : A)
System.out.println(t);
rotate(A);
}
}