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 ] ]
分析: 典型的题目 注意二维数组遍历的方式,“一圈圈”来遍历比较直接
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> matrix(n, vector<int>(n,0)); int len; int cnt=1; int x=0,y=0; for(int i=0; i*2<n; i++){ cout << "i = "<< i<<endl; // start point (i,i) len = n-i*2; x = y =i; if(len == 1) matrix[x][y] =cnt; // go right for(int j=0; j<len-1; j++){ matrix[x][y++] = cnt; cnt++; } // go down for(int j=0; j<len-1; j++){ matrix[x++][y] = cnt; cnt++; } // go left for(int j=0; j<len-1; j++){ matrix[x][y--] = cnt; cnt++; } // go up for(int j=0; j<len-1; j++){ matrix[x--][y] = cnt; cnt++; } } return matrix; } };
PS: 寒假开始, 每日重点就是leetcode, 两个星期看看能做多少