解题思路:
\qquad
这道题可以直接用模拟解决,顺时针螺旋可以分解为依次沿“右-下-左-上”四个方向的移动,每次碰到“边界”时改变方向,边界是不可到达或已经到达过的地方,会随着指针移动不断收缩。
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
int mode = 0, i = 0, j = 0;
int a = matrix[0].size(), b = matrix.size();
vector<int> bound = {a, b, -1, 0};
for(int m = 0; m < matrix.size() * matrix[0].size(); m++)
{
ans.push_back(matrix[i][j]);
switch(mode)
{
case 0:
if(j+1 >= bound[0])
{
bound[0] = j;
mode = (mode + 1) % 4;
i++;
}
else j++;
break;
case 1:
if(i + 1 >= bound[1])
{
bound[1] = i;
mode = (mode + 1) % 4;
j--;
}
else i++;
break;
case 2:
if(j-1 <= bound[2])
{
bound[2] = j;
mode = (mode + 1) % 4;
i--;
}
else j--;
break;
case 3:
if(i - 1 <= bound[3])
{
bound[3] = i;
mode = (mode + 1) % 4;
j++;
}
else i--;
break;
default:
break;
}
}
return ans;
}