题目:
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 ] ]
思路:
首先定义当前的四个边界,然后依次填充数据并更新位置。一旦发现新的位置越界,则更新位置和方向,并调整边界。算法的时间复杂度为O(n^2),空间复杂度为O(1)。
代码:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ret(n, vector<int>(n, -1));
int x = 0, y = 0, dx = 1, dy = 0;
int top = 0, bottom = n - 1, left = 0, right = n - 1; // defines the boundaries
for(int i = 1; i <= n * n; ++i)
{
ret[y][x] = i;
x += dx, y += dy;
if(x > right) // turn down
dx=0, dy=1, x--, y++, top++;
else if(y > bottom) // turn left
dx=-1, dy=0, x--, y--, right--;
else if(x < left) // turn up
dx=0, dy=-1, x++, y--, bottom--;
else if(y < top) // turn right
dx=1, dy=0, x++, y++, left++;
}
return ret;
}
};