29. 顺时针打印矩阵(spiralOrder)

29. 顺时针打印矩阵(spiralOrder)

1. python

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []
        left,top=0,0;
        right=len(matrix[0])
        bottom=len(matrix)
        ans=[]
        k =0
        while left<right and top<bottom:
            #from left to right
            for j in range(left,right):
                ans.append(matrix[top][j])
            top+=1
            #from top to bottom
            for i in range(top,bottom):
                ans.append(matrix[i][right-1])
            right-=1
            #from right to left
            for j in range(right-1,left-1,-1):
                if(top<bottom):
                    ans.append(matrix[bottom-1][j])
            bottom-=1
            #from bottom to top
            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 int[] spiralOrder(int[][] matrix) {
        if (matrix.length ==0 ||matrix==null){
            return new int[0];
        }
        int left=0;
        int top=0;
        int right=matrix[0].length;
        int bottom=matrix.length;
        int[] ans = new int[right*bottom];
        int k=0;
        while(left<right && top<bottom){
            for(int j=left;j<right;j++){
                ans[k++]=matrix[top][j];
            }
            top++;
            for(int i =top;i<bottom;i++){
                ans[k++]=matrix[i][right-1];
            }
            right--;
            for(int j=right-1;j>=left && top<bottom;j--){
                ans[k++]=matrix[bottom-1][j];
            }
            bottom--;
            for(int i=bottom-1;i>=top && left<right;i--){
                ans[k++]=matrix[i][left];
            }
            left++;
        }
        return ans;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值