-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMatrix.java
More file actions
78 lines (68 loc) · 1.47 KB
/
Matrix.java
File metadata and controls
78 lines (68 loc) · 1.47 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
package dataStructures.matrix;
public class Matrix {
private int[][] matrix;
public void set(int[][] m) {
if(m == null)
throw new IllegalArgumentException("Input matrix is NULL");
this.matrix = m;
}
public int[][] get() {
return matrix;
}
/**
* rotate matrix
* @return rotated matrix
* @time complexity O(n^2)
* @space complexity O(1)
*/
public void rotate() {
this.transpose();
this.reflect();
}
/**
* transpose matrix : 1 step -> rotated
* @time complexity O(n^2)
* @space complexity O(1)
*/
public void transpose() {
for (int i = 0; i < matrix.length; i++) {
for (int j = i; j < matrix[i].length; j++) {
int tmp = matrix[j][i];
matrix[j][i] = matrix[i][j];
matrix[i][j] = tmp;
}
}
}
/**
* reflect early transposed matrix : 2 step -> rotated
* @time complexity O(n^2)
* @space complexity O(1)
*/
public void reflect() {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length / 2; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[i][matrix.length - j - 1];
matrix[i][matrix.length - j - 1] = tmp;
}
}
}
@Override
public String toString() {
String out = "[";
for (int i = 0; i < matrix.length; i++) {
out = out + "[";
for (int j = 0; j < matrix.length; j++) {
out = out + matrix[i][j];
if (j != matrix.length - 1) {
out = out + ",";
}
}
out = out + "]";
if (i != matrix.length - 1) {
out = out + ",";
}
}
return out + "]";
}
}