解题思路
设置left、right、up、down,之后按顺序将二维数组的元素放入数组中,若四个变量变化过程中超出范围则break。
代码
class Solution {
public:vector<int> spiralOrder(vector<vector<int> > &matrix) {vector<int> res;if (matrix.size() == 0)return res;int m = matrix.size();int n = matrix[0].size();int left = 0, right = n - 1, up = 0, down = m - 1;while (1){for (int i = left; i <= right; i++)res.push_back(matrix[up][i]);if (++up > down)break;for (int i = up; i <= down; i++)res.push_back(matrix[i][right]);if (--right < left)break;for (int i = right; i >= left; i--)res.push_back(matrix[down][i]);if (--down < up)break;for (int i = down; i >= up; i--)res.push_back(matrix[i][left]);if (++left > right)break;}return res;}
};