-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution105.java
More file actions
39 lines (37 loc) · 862 Bytes
/
Solution105.java
File metadata and controls
39 lines (37 loc) · 862 Bytes
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
/*
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
*/
public class Solution {
public int[][] geneareteMatrix(int n) {
if (n < 1) return null;
int[][] matrix = new int[n][n];
int left = 0, right = n-1, top = 0, bottom = n-1;
int x = 0, y = 0, val = 1;
while (true) {
if (matrix[x][y] != 0) break;
if (x == top && y != right) {
matrix[x][y++] = val++;
} else if (x != bottom && y == right) {
matrix[x++][y] = val++;
} else if (x == bottom && y != left) {
matrix[x][y--] = val++;
} else if (x != top+1 && y == left) {
matrix[x--][y] = val++;
}else if (x == top+1 && y == left) {
left++;
right--;
top++;
bottom--;
}
}
return matrix;
}
}