题目链接:https://leetcode.com/problems/spiral-matrix/
题目:
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 ]
]
[1,2,3,6,9,8,7,4,5]
.
思路:
注意细节。
首先计算需要遍历几“圈”,将每圈分成四次不同方向的遍历。
算法:
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<Integer>();
if (matrix.length == 0) {
return list;
}
// n行m列
int n = matrix.length;
int m = matrix[0].length;
// dim是矩阵的圈数
int dim = Math.min(n, m) / 2;
if (Math.min(n, m) == 1) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
list.add(matrix[i][j]);
}
}
return list;
}
if (Math.min(n, m) % 2 != 0)
dim++;
for (int i = 0; i < dim; i++) {
for (int j = i; j < m - i; j++) {
list.add(matrix[i][j]);
}
if (i + 1 == (n - i))
break;
for (int x = i + 1; x < n - i; x++) {
list.add(matrix[x][m - i - 1]);
}
if (m - 2 - i < i)
break;
for (int x = m - 2 - i; x >= i && x < m && x >= 0; x--) {
list.add(matrix[n - 1 - i][x]);
}
for (int x = n - 2 - i; x > i; x--) {
list.add(matrix[x][i]);
}
}
return list;
}