标签:
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
1 class Solution { 2 public: 3 vector<vector<int> >generateMatrix(int n) { 4 int m=0; 5 vector<vector<int> >a; 6 a.resize(n,vector<int>(n)); 7 if(n==0) 8 return a; 9 int x=0; 10 int y=0; 11 m=a[0][0]=1; 12 13 while(m<n*n) 14 { 15 while(y<n-1&&!a[x][y+1]) 16 { 17 m++; 18 y++; 19 a[x][y]=m; 20 } 21 while(x<n-1&&!a[x+1][y]) 22 { 23 m++; 24 x++; 25 a[x][y]=m; 26 } 27 28 while(y-1>=0&&!a[x][y-1]) 29 { 30 m++; 31 y--; 32 a[x][y]=m; 33 } 34 35 while(x-1>=0&&!a[x-1][y]) 36 { 37 m++; 38 x--; 39 a[x][y]=m; 40 } 41 } 42 43 return a; 44 } 45 };
标签:
原文地址:http://www.cnblogs.com/jawiezhu/p/4474572.html