LeetCode Algorithmic Question: Spiral Order of Spiral Matrix

Keywords: network

Given a matrix containing m x n elements (m rows, n columns), return all elements in the matrix in a clockwise spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

Source: LeetCode
 Link: https://leetcode-cn.com/problems/spiral-matrix
 Copyright belongs to the seizure network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Thought: Add in circles and circles, pay attention to array crossing and topic rules

public List<Integer> spiralOrder(int[][] matrix) {
        if (matrix.length == 0 || matrix == null) return new ArrayList();//Array space-time
        int iLength = matrix.length;
        int jLength = matrix[0].length;

        int step = iLength * jLength;//How many elements are added?
        ArrayList<Integer> list = new ArrayList<>(step);

        int cur = 0, i = 0, j = 0;
        int ii = 0, jj = 0;
        while (cur < step) {//Each cycle represents a circle.

            if (cur > 0) {
                jLength -= 1;
                iLength -= 1;
                ii += 1;//Avoid adding added elements
                jj += 1;

            }

            while (cur < step && j < jLength) {
                list.add(matrix[i][j++]);
                cur++;
            }
            j--;//Avoid arrays crossing boundaries, as follows
            i++;
            while (cur < step && i < iLength) {
                list.add(matrix[i++][j]);
                cur++;
            }
            i--;
            j--;
            while (cur < step && j >= jj) {
                list.add(matrix[i][j--]);
                cur++;
            }
            j++;
            i--;
            while (cur < step && i > ii) {
                list.add(matrix[i--][j]);
                cur++;
            }
            i++;
            j++;
        }
        return list;

    }

Posted by happyneil on Tue, 08 Oct 2019 07:25:08 -0700