54. 螺旋矩阵(spiralOrder)

54. 螺旋矩阵(spiralOrder)

1. python

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:return []
        left,top=0,0
        right,bottom=len(matrix[0]),len(matrix)
        ans=[]
        while left<right and top<bottom:
            for j in range(left,right):
                ans.append(matrix[top][j])
            top+=1
            for i in range(top,bottom):
                ans.append(matrix[i][right-1])
            right-=1
            for j in range(right-1,left-1,-1):
                if top<bottom:
                    ans.append(matrix[bottom-1][j])
            bottom-=1
            for i in range(bottom-1,top-1,-1):
                if left<right:
                    ans.append(matrix[i][left])
            left+=1
        return ans

2. Java

class Solution {
    
    
    public List<Integer> spiralOrder(int[][] matrix) {
    
    
        if (matrix.length ==0 ||matrix==null){
    
    
            return new ArrayList(0);
        }
        int left=0;
        int top=0;
        int right=matrix[0].length;
        int bottom=matrix.length;
        List<Integer> ans = new ArrayList<Integer>() ;
        while(left<right && top<bottom){
    
    
            for(int j=left;j<right;j++){
    
    
                ans.add(matrix[top][j]);
            }
            top++;
            for(int i =top;i<bottom;i++){
    
    
                ans.add(matrix[i][right-1]);
            }
            right--;
            for(int j=right-1;j>=left && top<bottom;j--){
    
    
                ans.add(matrix[bottom-1][j]);
            }
            bottom--;
            for(int i=bottom-1;i>=top && left<right;i--){
    
    
                ans.add(matrix[i][left]);
            }
            left++;
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44294385/article/details/112391998