Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
java 中是传值的,将count作为返回值返回
1 public static int[][] generateMatrix(int n) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 if(n <= 0) 5 return new int[0][]; 6 7 int rows = n; 8 int cols = n; 9 int[][] result = new int[n][n]; 10 int count = 1; 11 12 int start = 0; 13 while (rows > start * 2 && cols > start * 2) { 14 count = printCircle(result, rows, cols, start, count, n * n); 15 start++; 16 } 17 18 return result; 19 } 20 21 public static int printCircle(int[][] matrix, int rows, int cols, 22 int start, int count, int n) { 23 int endX = cols - 1 - start; 24 int endY = rows - 1 - start; 25 26 // print row 27 for (int i = start; i <= endX && count <= n; i++) { 28 matrix[start][i] = count ++; 29 } 30 31 // print col 32 if (endY > start) { 33 for (int i = start + 1; i <= endY && count <= n; i++) { 34 matrix[i][endX] = count ++; 35 } 36 } 37 // print row 38 if (endX > start && endY > start) { 39 for (int i = endX - 1; i >= start && count <= n; i--) { 40 matrix[endY][i] = count ++; 41 } 42 } 43 // print col 44 if (endX > start && endY - 1 > start) { 45 for (int i = endY - 1; i > start && count <= n; i--) { 46 matrix[i][start] = count ++; 47 } 48 } 49 return count; 50 }