-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrixII.java
More file actions
49 lines (45 loc) · 811 Bytes
/
SpiralMatrixII.java
File metadata and controls
49 lines (45 loc) · 811 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
40
41
42
43
44
45
46
47
48
49
package com.mirraico.leetcode;
public class SpiralMatrixII {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
if(n == 0) return matrix;
int i = 0, j = 0, lev = 0, dir = 0, cnt = 1;
int num = n * n;
while(num > 1) {
switch(dir) {
case 0:
while(j < n - 1 - lev) {
matrix[i][j] = cnt++;
j++; num--;
}
dir++;
break;
case 1:
while(i < n - 1 - lev) {
matrix[i][j] = cnt++;
i++; num--;
}
dir++;
break;
case 2:
while(j > lev) {
matrix[i][j] = cnt++;
j--; num--;
}
dir++; lev++;
break;
case 3:
while(i > lev) {
matrix[i][j] = cnt++;
i--; num--;
}
dir = 0;
break;
}
}
matrix[i][j] = cnt++;
return matrix;
}
public static void main(String[] args) {
}
}