注意边界
1 public class Solution { 2 public int[][] generateMatrix(int n) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 if(n <= 0) 6 return new int[0][]; 7 int[][] matrix = new int[n][n]; 8 printCircle(matrix, 0, n, 1); 9 return matrix; 10 } 11 private void printCircle(int[][] matrix, int start, int end, int n) 12 { 13 if(start >= end) 14 return; 15 if(end - start == 1){ 16 matrix[start][start] = n; 17 return; 18 } 19 for(int i = start; i < end - 1; i++) 20 { 21 matrix[start][i] = n; 22 n++; 23 } 24 for(int i = start; i < end - 1; i++) 25 { 26 matrix[i][end - 1] = n; 27 n++; 28 } 29 for(int i = end - 1; i > start; i--) 30 { 31 matrix[end - 1][i] = n; 32 n++; 33 } 34 for(int i = end - 1; i > start; i--) 35 { 36 matrix[i][start] = n; 37 n++; 38 } 39 printCircle(matrix, start+1, end-1, n); 40 } 41 }