Given an integern, generate a square matrix filled with elements from 1 ton2in spiral order.For example,Givenn=3,You should return the following matri
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道蛇形取数差不多。
http://blog.csdn.net/accepthjp/article/details/52577112
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<int> row(n,0);
vector<vector<int>> result(n,row);
int rows=n,cols=n,cnt=0;
for(int x=0,y=0;x<rows && y<cols;x++,y++)
{
for(int i=y;i<cols;i++) result[x][i]=++cnt;
for(int i=x+1;i<rows;i++) result[i][cols⑴]=++cnt;
for(int i=cols⑵;i>=y;i--) result[rows⑴][i]=++cnt;
for(int i=rows⑵;i>x;i--) result[i][y]=++cnt;
rows--;
cols--;
}
return result;
}
};