leetcode54螺旋矩阵

在这里插入图片描述

package 剑指offer.数组;

import java.util.ArrayList;
import java.util.List;

/**
 *
 *  输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
 *    1  2  3
 *    4  5  6
 *    7  8  9
 *  输出:[1,2,3,6,9,8,7,4,5]
 *  坐标变化:(0,0)(0,1)(0,2) 拐弯(1,2)(2,2)拐弯(2,1)(2,0)拐弯(1,0) 拐弯(1,1)
 *
 *
 */
public class leetcode54螺旋矩阵 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<Integer>();
        //null矩阵 只有一行  或者一列 不行
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return order;
        }
        //获取行列
        int rows = matrix.length, columns = matrix[0].length;
        //构造是否访问过的visited矩阵
        boolean[][] visited = new boolean[rows][columns];
        //元素个数
        int total = rows * columns;

        //初始化row column
        int row = 0, column = 0;
        //对数组进行访问时的方向
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int directionIndex = 0;

        /**
         *    行变化      列变化
         *     0           1    (右走)
         *     1           0    (下走)
         *     0          -1    (左走)
         *    -1           0    (上走)
         *
         */

        for (int i = 0; i < total; i++) {
            //加入order数组
            order.add(matrix[row][column]);
            //visited矩阵
            visited[row][column] = true;
            //定义nextrow nextcolumn下一次要走的方向 判断是否拐弯
            int nextRow = row + directions[directionIndex][0];
            int nextColumn = column + directions[directionIndex][1];
            //当发生发生转弯的时候 有五种情况:
            //右侧碰到边界(nextColumn>=columns);左侧碰到边界(nextColumn < 0)
            //下侧碰到边界(nextRow >= rows);上侧碰到边界(nextRow < 0)
            //以及马上访问到已经访问过的元素
            if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns
                    || visited[nextRow][nextColumn]) {
                //2%4=2  4%4=0
                //开始转向 
                directionIndex = (directionIndex + 1) % 4;
            }

            row += directions[directionIndex][0];
            column += directions[directionIndex][1];
        }
        return order;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你们卷的我睡不着QAQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值