54. Spiral Matrix(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84110565

题目:

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:

Input: 
[  
[ 1, 2, 3 ],  
[ 4, 5, 6 ],  
[ 7, 8, 9 ] 
] 
Output:[1,2,3,6,9,8,7,4,5] 

Example 2:

Input: 
[   
[1, 2, 3, 4],   
[5, 6, 7, 8],   
[9,10,11,12] 
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

解释:
螺旋状(顺时针)遍历矩阵,剑指offer原题。
需要注意的是,start一定是在主对角线上的,也就是x和y的start是一样的。
python代码:

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if not matrix:
            return []
        self.rows=len(matrix)
        self.cols=len(matrix[0])
        start=0
        self.result=[]
        self.matrix=matrix
        def appendInCircle(start):
            endX=self.cols-1-start
            endY=self.rows-1-start
            #从左到右打印一行
            for i in xrange(start,endX+1):
                self.result.append(self.matrix[start][i])
            #从上到下打印一列
            if endY>start:
                for i in xrange(start+1,endY+1):
                    self.result.append(self.matrix[i][endX])
            #从右到左打印一行
            if endY>start and endX>start:
                for i in xrange(endX-1,start-1,-1):
                    self.result.append(self.matrix[endY][i])
            #从下到上打印一列,三行两列
            if endX>start and endY-start>1:
                for i in xrange(endY-1,start,-1):
                    self.result.append(self.matrix[i][start])
            
        while self.cols>start*2 and self.rows>start*2:
            appendInCircle(start)
            start+=1
        return self.result

c++代码:

class Solution {
public:
    vector <int> result;
    int row;
    int col;
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        row=matrix.size();
        if (row==0)
            return result;
        col=matrix[0].size();
        int start=0;
        while(2*start<row && 2*start<col)
        {
            appendInCircle(start,matrix);
            start++;
        }
       return result; 
        
    }
    void appendInCircle(int start,vector<vector<int>>& matrix)
    {
        int endX=col-1-start;
        int endY=row-1-start;
        //从左到右打印一行
        for(int i=start;i<=endX;i++)
            result.push_back(matrix[start][i]);
        //从上到下打印一列
        if (endY>start)
        {
            for(int i=start+1;i<=endY;i++)
                result.push_back(matrix[i][endX]);
        }
        //从右往左打印一行
        if(endY>start && endX>start)
        {
            for(int i=endX-1;i>=start;i--)
                result.push_back(matrix[endY][i]);
        }
        //从下往上打印一行
        if(endY-start>1 &&endX>start)
            for(int i=endY-1;i>start;i--)
                result.push_back(matrix[i][start]);
    }
};

总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/84110565