Spiral Matrix II
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 ] ]
类似题目 :Spiral Matrix
1 public class Solution { 2 public int[][] generateMatrix(int n) { 3 int[][] result = new int[n][n]; 4 if (n <= 0) { 5 return result; 6 } 7 int xStart = 0; 8 int yStart = 0; 9 int num = 1; 10 while (n > 0) { 11 if (n == 1) { 12 result[yStart][xStart] = num; 13 } 14 15 for (int i = 0; i < n - 1; i++) { 16 result[yStart][xStart + i] = num++; 17 } 18 for (int i = 0; i < n - 1; i++) { 19 result[yStart + i][xStart + n - 1] = num++; 20 } 21 for (int i = 0; i < n - 1; i++) { 22 result[yStart + n - 1][xStart + n - 1 - i] = num++; 23 } 24 for (int i = 0; i < n - 1; i++) { 25 result[yStart + n - 1 - i][xStart] = num++; 26 } 27 xStart++; 28 yStart++; 29 n = n - 2; 30 } 31 return result; 32 } 33 }

浙公网安备 33010602011771号