054_Spiral_Matrix

Spiral Matrix

Difficulty Medium

tags matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,

Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

用一下宏定义是很好的。

失误的case:

只考虑了常见的情况,而当只剩一行或一列时原算法会重复。 所以后来加了判别。

solution 1

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        #define A(i, j) matrix[i+x_off][j+y_off]
        vector<int> res;
        int m = matrix.size();
        int n = m==0? 0 : matrix[0].size();
        if (m==0 || n==0) return res;
        int x_off = 0, y_off = 0;
        while (m>0 && n>0) {
            for (int j=0; j<n; j++) {
                res.push_back(A(0, j));
            }
            for (int i=1; i<m; i++) {
                res.push_back(A(i, n-1));
            }
            if (m>1) {
                for (int j=n-2; j>=0; j--) {
                    res.push_back(A(m-1, j));
                }
            }
            if (n>1) {
                for (int i=m-2; i>=1; i--) {
                    res.push_back(A(i, 0));
                }
            }
            m = m-2;
            n = n-2;
            x_off++;
            y_off++;
        }
        return res;
    }
};
posted @ 2017-12-13 15:37  whensean  阅读(94)  评论(0)    收藏  举报