螺旋输出矩阵

该博客介绍了如何使用Java实现螺旋矩阵的遍历。作者提供了两种思路,一种是模拟矩阵的螺旋行走,另一种是逐层遍历。文章中给出了详细的代码实现,展示了如何从四个边界开始,依次访问矩阵的每一层元素,直到所有元素都被访问。这种方法对于理解和操作二维矩阵很有帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

螺旋矩阵

题目地址:螺旋矩阵

按照题意其实是有两种思路,一个是模拟题意行动,遇到超过边界的情况就转方向,设置一个visit访问矩阵,这种方法感觉很麻烦。
第二种是比较好理解的,把矩阵层层剥开,一层一层去访问,代码写起来也比较好理解。

package test;
import java.util.LinkedList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
       int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
       System.out.println(spiralOrder(matrix));
    }
    public static List<Integer> spiralOrder(int[][] matrix) {
        LinkedList<Integer> result = new LinkedList<>();
        if(matrix == null || matrix.length == 0) return result;
        //定义四个边角
        int top = 0;
        int left = 0;
        int bottom = matrix.length - 1;
        int right = matrix[0].length - 1;
        int numElm = matrix.length * matrix[0].length;//元素个数
        while(numElm >= 1){
            //最上层
            for(int i = left; i <= right && numElm >= 1; i++){
                result.add(matrix[top][i]);
                numElm--;
            }
            top++;
            //右边层
            for(int i = top; i <= bottom && numElm >= 1; i++){
                result.add(matrix[i][right]);
                numElm--;
            }
            right--;
            //最下层
            for(int i = right; i >= left && numElm >= 1; i--){
                result.add(matrix[bottom][i]);
                numElm--;
            }
            bottom--;
            //最左层
            for(int i = bottom; i >= top && numElm >= 1; i--){
                result.add(matrix[i][left]);
                numElm--;
            }
            left++;
        }
        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值