Leetcode054

054 螺旋矩阵

public class SpiralOrder054 {
    public static void main(String[] args) {
        // 正确顺序:123698745
        int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
        List<Integer> res = spiralOrder(matrix);
        for(Integer order : res){
            System.out.println(order);
        }
    }
    public static List<Integer> spiralOrder(int[][] matrix) {
        // 不需要一个flag标记位来表示遍历的方向,方向是固定的。边界可以由方向来决定
        // List<Integer> res = new ArrayList<>();
        // int width = matrix.length;//矩阵的行(宽度)
        // int length = matrix[0].length;//矩阵的列(长度)
        // int flag = 0;//0表示正序遍历行,1表示正序遍历列,-1表示倒序遍历行,-2表示倒序遍历列

        // while(width > 0 && length > 0){
        //     int row = 0;// 每一圈遍历的行和列
        //     int col = 0;
        //     //先遍历行
        //     if(flag == 0){
        //         for(int i = col; i < width; i++){
        //             res.add(matrix[row][i]);
        //         }
        //         flag = 1; //第一行遍历完之后,开始正序遍历列
        //         width--;  //第一行遍历完之后,下一次遍历行的时候宽度应该减1
        //     }
        //     if(flag == 1){
        //         for(int i = row; i < length; i++ ){
        //             res.add(matrix[i][col]);
        //         }
        //         flag = -1;
        //         length--;
        //     }
        // }
        List<Integer> res = new ArrayList<>();
        int left = 0;
        int top = 0;
        int bottom = matrix.length-1;
        int right = matrix[0].length-1;
        //定义四个角表示边界
        //那么遍历顺序应该是:
        // (top,left)-->(top,right)
        // (top+1,right)--->(bottom,right)
        // (bottom,right-1)--->(bottom,left+1)
        // (bottom,left)--->(top+1,left)
        while(left <= right && top <= bottom){
            for(int i = left; i <= right; i++){
                res.add(matrix[top][i]);
            }
            for(int i = top+1; i <= bottom; i++){
                res.add(matrix[i][right]);
            }
            if(left < right && top < bottom){
                for(int i = right-1; i > left; i--){
                    res.add(matrix[bottom][i]);
                }
                for(int i = bottom; i > top; i--){
                    res.add(matrix[i][left]);
                }
            }
            top++;
            bottom--;
            left++;
            right--;
        }
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值