59. Spiral Matrix II

和Spiral Matrix是一样的,这题还简单一点

 1     public int[][] generateMatrix(int n) {
 2     int[][] res = new int[n][n];
 3         if(n <= 0) {
 4             return res;
 5         }
 6         int layer = n / 2;
 7         int cnt = 1;
 8         for(int i = 0; i < layer; i++) {
 9             for(int j = i; j < n-1-i; j++) {
10                 res[i][j] = cnt;
11                 cnt++;
12             }
13             for(int j = i; j < n-1-i; j++) {
14                 res[j][n-1-i] = cnt;
15                 cnt++;
16             }
17             for(int j = i; j < n-1-i; j++) {
18                 res[n-1-i][n-1-j] = cnt;
19                 cnt++;
20             }
21             for(int j = i; j < n-1-i; j++) {
22                 res[n-1-j][i] = cnt;
23                 cnt++;
24             }
25         }
26         if(n % 2 == 1) {
27             res[layer][layer] = cnt;
28         }
29         return res;
30     }

 

你可能感兴趣的:(59. Spiral Matrix II)