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 ]
]
思路:这道题顺时针从1到n2放入数组,没啥高深数据结构或算法,直接顺时针打印就可以了。
class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> > matrix(n,vector<int>(n)); if(n<=0) return matrix; int sum=1; int start=0; while(start<(n+1)/2) { for(int i=start;i<=n-1-start;i++) { matrix[start][i]=sum++; } for(int i=start+1;i<=n-1-start;i++) { matrix[i][n-1-start]=sum++; } for(int i=n-2-start;i>=start;i--) { matrix[n-1-start][i]=sum++; } for(int i=n-2-start;i>=start+1;i--) { matrix[i][start]=sum++; } start++; } return matrix; } };