题解 | #螺旋矩阵#

螺旋矩阵

http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31

class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
    vector<int>ret;
    if (matrix.empty())return ret;
    int m = matrix.size();
    int n = matrix[0].size();
    if (m == 1 && n == 1)return { 1 };
    int top = 0, down = m - 1, l = 0, r = n - 1;
    int i = 0, k = 0, j = 0;
    if (m == 0)return ret;
    while (i < m*n) {
        k = l;
        while (i < m*n&&k <=r) {
            ret.push_back(matrix[top][k]);
            k++;
            i++;
        }
        top++;
        j = top;
        while (i < m*n&&j <= down) {
            ret.push_back(matrix[j][r]);
            j++;
            i++;
        }
        r--;
        k = r;
        while (i < m*n&&k >=l) {
            ret.push_back(matrix[down][k]);
            k--;
            i++;
        }
        down--;
        j = down;
        while (i < m*n&&j >= top) {
            ret.push_back(matrix[j][l]);
            j--;
            i++;
        }
        l++;
    }
    return ret;
}
};

其实可以通过设置游标k,j,通过限制上下左右来进行遍历即可

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务