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 ]
]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int[][] generateMatrix(int n) { 3 int []count = {1}; 4 int [][] m = new int[n][n]; 5 int start = 0; 6 while(start<=n/2){ 7 fill(m,start,count); 8 start++; 9 } 10 return m; 11 } 12 public void fill(int[][]m,int start,int[]count){ 13 int end = m.length-start-1; 14 //up 15 for(int i=start;i<=end;i++){ 16 m[start][i] = count[0]++; 17 } 18 //right 19 for(int i=start+1;i<=end;i++){ 20 m[i][end] = count[0]++; 21 } 22 //down 23 for(int i=end-1;i>=start;i--){ 24 m[end][i] = count[0]++; 25 } 26 //left 27 for(int i=end-1;i>start;i--){ 28 m[i][start] = count[0]++; 29 } 30 } 31 }