54. Spiral Matrix 「螺旋矩阵」

给定一个 m×n 的矩阵(m 行,n 列),以螺旋顺序返回所有元素。

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

例二:
输入: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
输出: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

这个题就是以螺旋升天的方式读出所有的数。

思路还是挺好想的,就是通过改变 ij 来读取四个方向上的数字,至于每个方向每次读取多少个,就用一个 length - x/2 来表示。其中 length 为每个方向上的矩阵的长度,即长或高,每次减去一定的数就可以得到将要读取的次数了,至于为什么是 x/2,纯粹是画了一下图分析出来的数学规律?。length 何时是高何时是宽,方向怎么确定,就直接用个数字除以 24 取余来确定就可以了。
看起来用了两个嵌套的 for 循环,但是时间复杂度并不高,只有 O(N)N 为数组元素的数量。

/*
 * 54. Spiral Matrix
 * https://leetcode.com/problems/spiral-matrix/
 * https://www.whosneo.com/54-spiral-matrix/
 */

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

public class SpiralOrder {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12}
        };

        SpiralOrder solution = new SpiralOrder();
        solution.print(matrix);
        List<Integer> result = solution.spiralOrder(matrix);
        System.out.println(result);
    }

    private List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0)
            return result;
        int m = matrix.length, n = matrix[0].length, target = m * n;
        int i = 0, j = -1;

        for (int x = 1, length = 0, direction = 0; result.size() < target; x++, direction++) {
            switch (direction % 2) {
                case 0: length = n; break;
                case 1: length = m; break;
            }
            for (int step = 0; step < length - x / 2; step++) {
                switch (direction % 4) {
                    case 0: j++; break;
                    case 1: i++; break;
                    case 2: j--; break;
                    case 3: i--; break;
                }
                result.add(matrix[i][j]);
            }

        }

        return result;
    }

    private void print(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        System.out.println("[");
        for (int i = 0; i < m; i++) {
            System.out.print(" [");
            for (int j = 0; j < n; j++) {
                System.out.print(matrix[i][j]);
                if (j < n - 1)
                    System.out.print(", ");
            }
            System.out.print("]");
            if (i < m - 1)
                System.out.print(",");
            System.out.println();
        }
        System.out.println("]");
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注