-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq059_SpiralMatrix2.java
More file actions
58 lines (53 loc) · 1.4 KB
/
q059_SpiralMatrix2.java
File metadata and controls
58 lines (53 loc) · 1.4 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
package leetcode_algorithm;
import java.util.Arrays;
/**
* Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
* <p>
* For example,
* Given n = 3,
* <p>
* You should return the following matrix:
* [
* [ 1, 2, 3 ],
* [ 8, 9, 4 ],
* [ 7, 6, 5 ]
* ]
*/
public class q059_SpiralMatrix2 {
public static void main(String[] args) {
System.out.println(Arrays.deepToString(new q059_SpiralMatrix2().generateMatrix(3)));
}
/**
* ½â·¨1(¸öÈ˽ⷨ)
*
* @param n
* @return
*/
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int rowBegin = 0;
int colBegin = 0;
int rowEnd = n - 1;
int colEnd = n - 1;
int index = 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
for (int i = colBegin; i <= colEnd; i++) {
result[rowBegin][i] = index++;
}
rowBegin++;
for (int i = rowBegin; i <= rowEnd; i++) {
result[i][colEnd] = index++;
}
colEnd--;
for (int i = colEnd; i >= colBegin; i--) {
result[rowEnd][i] = index++;
}
rowEnd--;
for (int i = rowEnd; i >= rowBegin; i--) {
result[i][colBegin] = index++;
}
colBegin++;
}
return result;
}
}