首页 > 代码库 > [LeetCode] Spiral Matrix II

[LeetCode] Spiral Matrix II

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

 

[LeetCode] Spiral Matrix II