题目链接:
剑指 Offer 29 顺时针打印矩阵
题解:
class Solution
{
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
vector<int> res;
if(!matrix.size())
return res;
int l = 0, r = matrix[0].size() - 1, t = 0, b = matrix.size() - 1;
while(1)
{
for(int i = l; i <= r; ++i)
res.push_back(matrix[t][i]);
if(++t > b)
break;
for(int i = t; i <= b; ++i)
res.push_back(matrix[i][r]);
if(--r < l)
break;
for(int i = r; i >= l; --i)
res.push_back(matrix[b][i]);
if(--b < t)
break;
for(int i = b; i >= t; --i)
res.push_back(matrix[i][l]);
if(++l > r)
break;
}
return res;
}
};
解题思路:
思路看代码就可以看出来,只不过需要注意边界条件,不要超界