首页 > 代码库 > 【LeetCode】Spiral Matrix

【LeetCode】Spiral Matrix

Spiral Matrix

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

 

每层以(i,i)位置出发,向右到达(i,n-1-i),向下到达(m-1-i,n-1-i),向左到达(m-1-i,i),再向上回到起点。

所有层次遍历完成后,即得到所求数组

需要注意的是,当只剩一行或者一列,也就是i==m-1-i或者i==n-1-i时,不要来回重复遍历。

class Solution {public:    vector<int> spiralOrder(vector<vector<int> > &matrix) {        vector<int> result;        if(matrix.empty() || matrix[0].empty())            return result;        int m = matrix.size();        int n = matrix[0].size();                int minSize = min(m,n);        int level = (minSize%2==0)?(minSize/2):(minSize/2+1);        for(int i = 0; i < level; i ++)        {//start with matrix[i][i]            //from up-left to up-right, row i            for(int j = i; j < n-i; j ++)                result.push_back(matrix[i][j]);            //from up-right to down-right, col n-1-i            for(int j = i+1; j < m-i; j ++)                result.push_back(matrix[j][n-1-i]);            //from down-right to down-left, row m-1-i            if(m-1-i != i)            {//last row                for(int j = n-1-i-1; j >= i; j --)                    result.push_back(matrix[m-1-i][j]);            }            //from down-left to up-left            if(i != n-1-i)            {//last col                for(int j = m-1-i-1; j > i; j --)                    result.push_back(matrix[j][i]);            }        }        return result;    }};

【LeetCode】Spiral Matrix