首页 > 学院 > 开发设计 > 正文

LeetCode 54. Spiral Matrix

2019-11-08 02:23:25
字体:
来源:转载
供稿:网友

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].

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;    }    };


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表