LeetCode-100题(Hot) 54. 螺旋矩阵 [Java实现] [极速]

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

示例 1:

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

提示:

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

由题分析可得,可以将走过的路设置为 matrix[i][j] 取值范围外的值例如 -101,当走到转角 (数组边界 / matrix[i][j] == -101) 处按照顺时针进行对应转向,当无路可走 (数组越界 / matrix[i][j] == -101) 时终止循环。实现如下:

    private int width;
    private int height;

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>((height = matrix.length) * (width = matrix[0].length));
        int value;
        while ((value = getNext(matrix)) != -101) result.add(value);
        return result;
    }

    public static final int LEFT = 1;
    public static final int RIGHT = 2;
    public static final int UP = 3;
    public static final int DOWN = 4;
    private int vector = RIGHT;
    private int x = 0, y = 0;
    private int getNext(int[][] map) {
        if (x < 0 || y < 0 || x == width || y == height || map[y][x] == -101) return -101;
        int value = map[y][x];
        map[y][x] = -101; // 标记走过

        switch (vector) {
            case LEFT:
                if (x-1 < 0 || map[y][x-1] == -101) {
                    vector = UP;
                    -- y;
                } else {
                    -- x;
                }
                break;
            case RIGHT:
                if (x+1 >= width || map[y][x+1] == -101) {
                    vector = DOWN;
                    ++ y;
                } else {
                    ++ x;
                }
                break;
            case UP:
                if (y-1 < 0 || map[y-1][x] == -101) {
                    vector = RIGHT;
                    ++ x;
                } else {
                    -- y;
                }
                break;
            case DOWN:
                if (y+1 >= height || map[y+1][x] == -101) {
                    vector = LEFT;
                    -- x;
                } else {
                    ++ y;
                }
                break;
        }

        return value;
    }

                                

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值