0
点赞
收藏
分享

微信扫一扫

LeetCode 54. Spiral Matrix

時小白 2023-09-05 阅读 15


m x n elements (m rows, n

For example,
Given the following matrix:


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


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

answer:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        if(matrix.empty()) return result;
        int nLength = matrix[0].size(),mLength = matrix.size();
        int n = nLength - 1;
        int m = 0;
//        cout << nLength << " " << mLength << endl;
        
        while(nLength > 0 && mLength > 0){
            for(int i = 0; i < nLength; i ++)
                result.push_back(matrix[m][i + m]);
            
            for(int i = 1; i < mLength; i ++)
                result.push_back(matrix[i + m][n]);
            if(nLength == 1){
                return result;
            }
            for(int i = nLength - 2; i >= 0 && mLength > 1; i --)
                result.push_back(matrix[m + mLength - 1][i + m]);
            for(int i = mLength - 2 ; i > 0; i --)
                result.push_back(matrix[i + m][m]);
            mLength -= 2;
            nLength -= 2;
            m ++;
            n --;
        }
        return result;
    }
    
};




举报

相关推荐

0 条评论