标签:add pre mil lin public wrap content font ace
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
public class Solution { public int[][] generateMatrix(int n) { int [][]a=new int[n][n]; int val=0; for(int layer=0;layer<n/2;++layer){ int first=layer; int last=n-1-layer; for(int i=first;i<last;++i){ val++; a[first][i]=val; } for(int j=first;j<last;j++){ val++; a[j][last]=val; } for(int k=last;k>first;k--){ val++; a[last][k]=val; } for(int l=last;l>layer;l--){ val++; a[l][first]=val; } } if(n%2!=0) a[n/2][n/2]=n*n; return a; } }
标签:add pre mil lin public wrap content font ace
原文地址:http://www.cnblogs.com/liguangsunls/p/6785771.html