LeetCode (Spiral Matrix)

来源:互联网 发布:微信中打开淘宝网址 编辑:程序博客网 时间:2024/05/16 23:55

Problem:

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

Solution:

class Solution {public:    vector<int> spiralOrder(vector<vector<int>>& matrix) {        vector<int> ans;        if(matrix.empty()) return ans;        int m = matrix.size();        int n = matrix[0].size();        if(m == 1) return matrix[0];        for(int i = 0; i < n; i++)            ans.push_back(matrix[0][i]);        vector<vector<int>> m1;        for(int j = n - 1; j >= 0; j--){            vector<int> p;            for(int i = 1; i < m; i++)                p.push_back(matrix[i][j]);            m1.push_back(p);        }        vector<int> temp = spiralOrder(m1);        ans.insert(ans.end(), temp.begin(), temp.end());        return ans;    }};


0 0
原创粉丝点击