Leetcode 54. Spiral Matrix

来源:互联网 发布:淘宝宠物狗 编辑:程序博客网 时间:2024/06/15 03:59

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) {        if (matrix.size() == 0) return vector<int>();        int top = 0;        int bottom = matrix.size() - 1;        int left = 0;        int right = matrix[0].size() - 1;        vector<int> ret;        while (left <= right) {            for (int i = left; i <= right; ++i) {                ret.push_back(matrix[top][i]);            }            ++top;            if (top > bottom) break;             for (int i = top; i <= bottom; ++i){                ret.push_back(matrix[i][right]);            }            --right;            if (left > right) break;            for (int i = right; i >= left; --i) {                ret.push_back(matrix[bottom][i]);            }            --bottom;            if (bottom < top) break;            for (int i = bottom; i >= top; --i) {                ret.push_back(matrix[i][left]);            }            ++left;        }        return ret;    }};

略优化

class Solution {public:    vector<int> spiralOrder(vector<vector<int>>& matrix) {        int nrows = matrix.size();        if (nrows == 0) return vector<int>();        int ncols = matrix[0].size();        // setp long;        int top = 0;        int bottom = 0;        int left = 0;        int right = 0;        vector<int> ret;        while (left + right < ncols) {            copy(matrix[top].begin() + left, matrix[top].end() - right , back_inserter(ret));                    ++top;            if (top + bottom == nrows) break;             for (int i = top; i != nrows - bottom; ++i){                ret.push_back(matrix[i][ncols - 1 - right]);            }            ++right;            if (left + right == ncols) break;            copy(matrix[nrows - 1 - bottom].rbegin() + right, matrix[nrows - 1- bottom].rend() - left, back_inserter(ret));            ++bottom;            if (bottom + top == nrows) break;            for (int i = nrows - 1 - bottom; i >= top; --i) {                ret.push_back(matrix[i][left]);            }            ++left;        }        return ret;    }};
原创粉丝点击