版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/musechipin/article/details/82804310
模拟转圈即可。假设图纸无限大(可以越界),只有真正落在给出的棋盘范围的坐标才被记录下来。
转圈有两个规则:
1.步长从1开始,每走两个方向则步长增加1;
2.每走完一个步长,方向换一个;
我用了一个参数d记录走了多少步。d被2整除的时候说明要增加步长,接下来要走的方向是(d%4)。
速度打败100%。
class Solution {
public:
vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {
vector<vector<int>> direct = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
vector<vector<int>> res;
int count = 1;
int step = 1;
int d = 0;
int s = 1;
res.push_back({ r0, c0 });
while (count < R*C)
{
for (int i = 1; i <= step; i++)
{
int tmp = d % 4;
r0 += direct[tmp][0];
c0 += direct[tmp][1];
if ((r0 < R) && (c0 < C) && (r0 >= 0) && (c0>= 0))
{
res.push_back({r0, c0});
count++;
if (count == R*C) break;
}
}
d++;
if (d % 2 == 0) step++;
}
return res;
}
};
相关题目:
54. Spiral Matrix的C++解法
59. Spiral Matrix II的C++解法