54. Spiral Matrix

题目链接

https://leetcode.com/problems/spiral-matrix/

解题思路

按照题目要求输出结果就可以。

代码

class Solution {
public:
    vector spiralOrder(vector>& matrix) {
        vector ans;
        if (matrix.size() == 0) {
            return ans;
        }
        //上下左右四个边界
        int up = 0, down = matrix.size() - 1, left = 0, right = matrix[0].size() - 1;
        while (up <= down && left <= right) {
            //从左到右
            if (up < matrix.size()) {
                for (int i = left; i <= right; ++i) {
                    ans.push_back(matrix[up][i]);
                }
                up++;
            }

            //从上到下
            if (right >= 0) {
                for (int i = up; i <= down; ++i) {
                    ans.push_back(matrix[i][right]);
                }
                right--;
            }

            //从右往左
            if (down >= up) {
                for (int i = right; i >= left; --i) {
                    ans.push_back(matrix[down][i]);
                }
                down--;
            }

            //从下到上
            if (left <= right) {
                for (int i = down; i >= up; --i) {
                    ans.push_back(matrix[i][left]);
                }
                left++;
            }
        }
        return ans;
    }
};

你可能感兴趣的:(54. Spiral Matrix)