59. 螺旋矩阵 II - 力扣(Leetcode)

MyCodes:

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
import java.util.Scanner;

//螺旋矩阵II 59
class SpiralMatrixII59 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);

System.out.print("请输入 n = ");

int n = input.nextInt();

int[][] res = generateMatrix(n);
System.out.println("\n" + n + " 的螺旋矩阵为:");

for(int[] itemGroup : res){
for(int item : itemGroup){
System.out.print(item + "\t");
}
System.out.println();
}
input.close();
}
public static int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int start = 0;//起始点
int loop = 0;//控制循环次数
int count = 1;//填充 num
int i,j;

while (loop++ < n / 2){

//上
for (j = start; j < n - loop; j++){
res[start][j] = count++;
}
//右
for (i = start; i < n - loop; i++){
res[i][j] = count++;
}
//下
for (; j >= loop; j--){
res[i][j] = count++;
}
//左
for (; i >= loop; i--){
res[i][j] = count++;
}

//改变起始点
start++;
}

//n 为奇数,填充 (n/2, n/2)= n*n;
if (n % 2 == 1) {
res[start][start] = count;
}
return res;
}
}