59. Spiral Matrix II java solutions
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 ] ]
1 public class Solution { 2 public int[][] generateMatrix(int n) { 3 int startx = 0,starty = 0,endx = n-1,endy = n-1; 4 int[][] ans = new int[n][n]; 5 int count = 1; 6 while(startx <= endx && starty <= endy){ 7 for(int i = startx;i<=endx;i++){ 8 ans[starty][i] = count++; 9 } 10 starty++; 11 12 for(int i = starty;i<=endy;i++){ 13 ans[i][endx] = count++; 14 } 15 endx--; 16 17 for(int i = endx;i>=startx;i--){ 18 ans[endy][i] = count++; 19 } 20 endy--; 21 22 for(int i = endy;i>=starty;i--){ 23 ans[i][startx] = count++; 24 } 25 startx++; 26 } 27 return ans; 28 } 29 }
模拟螺旋打印的过程即可。