54. Spiral Matrix

来源:互联网 发布:java位运算实现加法 编辑:程序博客网 时间:2024/06/02 05:30

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

方法:circle by circle, 

class Solution {public:    vector<int> spiralOrder(vector<vector<int>>& m) {    vector<int> res;    int rows = m.size();    if (rows == 0) return res;    int cols = m[0].size();    for (int start = 0; start < (min(rows, cols) + 1) / 2; start++){    int L = cols - 2 * start, R = rows - 2 * start;    if (R == 1)    for (int i = 0; i < L; i++) res.push_back(m[start][start + i]);    else if (L == 1)    for (int i = 0; i < R; i++) res.push_back(m[start + i][start]);    else{    for (int i = 0; i < L - 1; i++) res.push_back(m[start][start + i]);    for (int i = 0; i < R - 1; i++) res.push_back(m[start + i][start + L - 1]);    for (int i = 0; i < L - 1; i++) res.push_back(m[start + R - 1][start + L - 1 - i]);    for (int i = 0; i < R - 1; i++) res.push_back(m[start + R - 1 - i][start]);    }    }    return res;    }};




0 0
原创粉丝点击