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
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.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;
jj += 1;

}

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