Spiral Matrix

来源:互联网 发布:淘宝卖家怎么发货的 编辑:程序博客网 时间:2024/06/11 09:56

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


class Solution {public:    vector<int> spiralOrder(vector<vector<int> > &matrix) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int m = matrix.size();        vector<int> result;        if (m==0)            return result;                    if (m==1){            result = matrix[0];            return result;        }                int n = matrix[0].size();               for(int i = 0; i< n/2; i++){            for (int j = i; j < n-1-i;j++)                result.push_back(matrix[i][j]);                            for (int j = i; j < m -1-i; j++)                result.push_back(matrix[j][n-1-i]);            for (int j = n-1-i; j>i; j--  )                result.push_back(matrix[m-1-i][j]);            for (int j = m-1-i; j>i;j--)                result.push_back(matrix[j][i]);                        }       if (n%2 != 0){           for (int j = n/2; j<m-n/2;j++)                result.push_back(matrix[j][n/2]);                    }                return result;    }};


原创粉丝点击