leetcode——54——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].


方法一:
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> ret;
        if(matrix.empty() || matrix[0].empty())
            return ret;
        
        int m = matrix.size();
        int n = matrix[0].size();
        int layer = (min(m,n)+1) / 2;
        for(int i = 0; i < layer; i ++)
        {
            //row i: top-left --> top-right
            for(int j = i; j < n-i; j ++)
                ret.push_back(matrix[i][j]);
                
            //col n-1-i: top-right --> bottom-right
            for(int j = i+1; j < m-i; j ++)
                ret.push_back(matrix[j][n-1-i]);
                
            //row m-1-i: bottom-right --> bottom-left
            if(m-1-i > i)
            {
                for(int j = n-1-i-1; j >= i; j --)
                    ret.push_back(matrix[m-1-i][j]);
            }
                
            //col i: bottom-left --> top-left
            if(n-1-i > i)
            {
                for(int j = m-1-i-1; j > i; j --)
                    ret.push_back(matrix[j][i]);
            }
        }
        return ret;
    }
};
方法二:
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.empty())
            return vector<int>();

        vector<int> ret;

        //输入矩阵行数
        int m = matrix.size() - 1;

        //输入矩阵的列数
        int n = matrix[0].size() - 1;

        for (int x = 0, y = 0; x <= m && y <= n; x++, y++)
        {
            //输出矩阵首行
            for(int j=y ; j<=n ; ++j)
            {
                ret.push_back(matrix[x][j]);
            }//while


            //输出矩阵最右列
            for (int i = x + 1; i <= m; ++i)
            {
                ret.push_back(matrix[i][n]);
            }//while

            //输出矩阵最底行
            for (int j = n - 1; j >= y && x != m; --j)
            {
                ret.push_back(matrix[m][j]);
            }

            //输出矩阵最左列
            for (int i = m - 1; i > x && y != n; --i)
            {
                ret.push_back(matrix[i][y]);
            }

            m--;
            n--;
        }//for

        return ret;

    }
};


你可能感兴趣的:(LeetCode,算法题)