leetcode 54. 螺旋矩阵 、面试题29. 顺时针打印矩阵【数组】

定义四个变量分别表示矩阵上、下、左、右的行或列,然后按顺时针顺序遍历这些行或列,遍历过的行或列用四个变量的自增或自减来去除,没遍历完一行或一列后,都需要判断是否遍历完整个矩阵,否则会添加多余元素。

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int height = matrix.length;
        if(height == 0)return res;
        int width = matrix[0].length;              
        int l=0, r=width-1, t = 0, b = height-1;
        while(res.size()<=(width)*(height) && t<=b && l<=r){
            for(int i=l; i<=r; i++){
                res.add(matrix[t][i]);                
            }
            if(++t>b)break;
            for(int i=t; i<=b; i++){
                res.add(matrix[i][r]);                
            }
            if(--r<l)break;
            for(int i = r; i>=l; i--){
                res.add(matrix[b][i]);              
            }
            if(--b<t)break;
            for(int i=b; i>=t; i--){
                res.add(matrix[i][l]);  
            }
            if(++l>r)break;
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值