-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
40 lines (36 loc) · 1.11 KB
/
Solution.java
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
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int i = 0,
j = 0,
topLimit = 0,
leftLimit = 0,
bottomLimit = n - 1,
rightLimit = n - 1,
xDirection = 1,
yDirection = 0;
for (int v = 1, max = (int) Math.pow(n, 2); v <= max; v++) {
matrix[i][j] = v;
if (j + xDirection > rightLimit) {
topLimit = i + 1;
xDirection = 0;
yDirection = 1;
} else if (i + yDirection > bottomLimit) {
rightLimit = j - 1;
xDirection = -1;
yDirection = 0;
} else if (j + xDirection < leftLimit) {
bottomLimit = i - 1;
xDirection = 0;
yDirection = -1;
} else if (i + yDirection < topLimit) {
leftLimit = j + 1;
xDirection = 1;
yDirection = 0;
}
i += yDirection;
j += xDirection;
}
return matrix;
}
}