螺旋矩阵(简单实现)

题目

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 :
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]

注意点

1、定义上、下、左、右是为了确定遍历的开始和结束的位置;
2、遍历过程中,需要判断count是否大于0;(是否遍历完成)
3、顺时针遍历,遍历完哪一行,哪一行加一(或减一);
4、遍历过程如下图:
在这里插入图片描述

实现

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return result;
        
        int top = 0; //上
        int bottom = matrix.length - 1; //下
        int left = 0; //左
        int right = matrix[0].length - 1; //右
        int count = matrix.length * matrix[0].length; //遍历的总数
        
        while (count > 0){
        	//从左往右遍历上行
            for(int i = left; i <= right && count > 0; i ++){
                result.add(matrix[top][i]);
                count --;
            }
            //遍历完上行,上行加一
            top ++;
            
            //从上往下遍历右行
            for (int i = top; i <= bottom && count > 0; i ++){
                result.add(matrix[i][right]);
                count --;
            }
            //遍历完右行,右行减一
            right --;
			
			//从右往左遍历下行
            for (int i = right; i >= left && count > 0; i --){
                result.add(matrix[bottom][i]);
                count --;
            }
            //遍历完下行,下行减一
            bottom --;

			//从下往上遍历左行
            for (int i = bottom; i >= top && count > 0; i --){
                result.add(matrix[i][left]);
                count --;
            }
            //遍历完左行,左行加一
            left ++;
        }
        
        return result;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值