问题描述
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return[1,2,3,6,9,8,7,4,5].
问题分析
不需要什么算法,螺旋打印即可。
代码实现
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<>();
if (matrix.length == 0) return res;
int m = matrix.length, n = matrix[0].length;
// 计算圈数
int lvl = (Math.min(m, n) + 1) / 2;
for (int i = 0; i < lvl; i++) {
int lastRow = m - i - 1;
int lastCol = n - i - 1;
if (i == lastRow) {
for (int j = i; j <= lastCol; j++) {
res.add(matrix[i][j]);
}
} else if (i == lastCol) {
for (int j = i; j <= lastRow; j++) {
res.add(matrix[j][i]);
}
} else {
for (int j = i; j < lastCol; j++) {
res.add(matrix[i][j]);
}
for (int j = i; j < lastRow; j++) {
res.add(matrix[j][lastCol]);
}
for (int j = lastCol; j > i; j--) {
res.add(matrix[lastRow][j]);
}
for (int j = lastRow; j > i; j--) {
res.add(matrix[j][i]);
}
}
}
return res;
}
网友评论