算法小解:54. 螺旋矩阵

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

 解:边界收缩,定义四个边界top,right,bottom,left。顺时针遍历矩阵时,如果撞墙了,更换方向,并且收缩自己遍历的那个边界,(比如说1 -> 2 -> 3,遇到了right,跟换遍历方向,并且收缩top边界(top++))。直到边界收缩到top > bottom或者left > right。

思路:Krahets

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        // 边界收缩
        if (matrix.length == 0) {
            return new ArrayList<Integer>();
        }
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;
        Integer[] res = new Integer[matrix.length * matrix[0].length];
        int x = 0;
        while (true) {
            for (int i = left; i <= right; i++) {
                res[x++] = matrix[top][i];
            }
            if (++top > bottom) break; // 上边界收缩
            for (int i = top; i <= bottom; i++) {
                res[x++] = matrix[i][right];
            }
            if (--right < left) break; // 右边界收缩
            for(int i = right; i >= left; i--) {
                res[x++] = matrix[bottom][i];
            }
            if(--bottom < top) break; // 下边界收缩
            for(int i = bottom; i >= top; i--){
                res[x++] = matrix[i][left];
            }
            if(++left > right) break; // 左边界收缩
        }
        return Arrays.asList(res);
    }
}
  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值