Leetcode 54. 螺旋矩阵(C、C++、python)

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]

示例 2:

输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

C

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* spiralOrder(int** matrix, int matrixRowSize, int matrixColSize) 
{
    int m=matrixRowSize;
    int n=matrixColSize;
    int su=m*n;
    int* res=(int*)malloc(sizeof(int)*su);
    int cc=0;
    int k=0;
    int count=(m+1)/2;
    while(k

C++

class Solution {
public:
    vector spiralOrder(vector>& matrix) 
    {
        vector res;
        if(matrix.empty() || matrix[0].empty())
        {
            return res;
        }
        int m=matrix.size();          
        int n=matrix[0].size();
        int su=m*n;
        int count=(m+1)/2;
        int k=0;
        int cc=0;
        while(k

C++ 法2

class Solution {
public:
    vector spiralOrder(vector>& matrix) 
    {
        vector res;
        if(0==matrix.size()  || 0==matrix[0].size())
        {
            return res;
        }
        int m=matrix.size();
        int n=matrix[0].size();
        int r=0,c=0;
        while(m>=2 && n>=2)
        {
            for(int j=c;j=c;j--)
            {
                res.push_back(matrix[r+m-1][j]);
            }
            for(int i=r+m-2;i>r;i--)
            {
                res.push_back(matrix[i][c]);
            }
            r++;
            c++;
            m-=2;
            n-=2;
        }
        if(m>0 && n>0)
        {
            if(m>n)
            {
                for(int i=r;i

 

python

class Solution:
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        res=[]
        m=len(matrix)
        if m==0:
            return res
        else:
            n=len(matrix[0])
            if n==0:
                return res
        count=(m+1)//2
        k=0
        su=m*n
        cc=0
        while k

 

你可能感兴趣的:(LeetCode)