Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in 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]
这个题就是以螺旋升天的方式读出所有的数。
思路还是挺好想的,就是通过改变 i
和 j
来读取四个方向上的数字,至于每个方向每次读取多少个,就用一个 length - x/2
来表示。其中 length
为每个方向上的矩阵的长度,即长或高,每次减去一定的数就可以得到将要读取的次数了,至于为什么是 x/2
,纯粹是画了一下图分析出来的数学规律🤪。length
何时是高何时是宽,方向怎么确定,就直接用个数字除以 2
或 4
取余来确定就可以了。
看起来用了两个嵌套的 for
循环,但是时间复杂度并不高,只有 O(N)
,N
为数组元素的数量。
/*
* 54. Spiral Matrix
* https://leetcode.com/problems/spiral-matrix/
* https://realneo.me/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("]");
}
}