给定一个 m*n 的矩阵,以螺旋顺序返回该矩阵的所有元素。
例如,给定矩阵:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
返回 [1,2,3,6,9,8,7,4,5]。
思路:从外到内分圈处理。
public class Solution {
public static List spiralOrder(int[][] matrix) {
List result = new ArrayList();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
int topRow = 0;
int leftCol = 0;
int bottomRow = matrix.length - 1;
int rightCol = matrix[0].length - 1;
while (topRow <= bottomRow && leftCol <= rightCol) {
spiralOrderCircle(matrix, topRow, leftCol, bottomRow, rightCol, result);
topRow++;
leftCol++;
bottomRow--;
rightCol--;
}
return result;
}
private static void spiralOrderCircle(int[][] matrix, int topRow,
int leftCol, int bottomRow, int rightCol, List result) {
if (topRow == bottomRow) {
spiralOrderRow(matrix, topRow, leftCol, rightCol, result);
} else if (leftCol == rightCol) {
spiralOrderCol(matrix, leftCol, topRow, bottomRow, result);
} else {
spiralOrderTop(matrix, topRow, leftCol, bottomRow, rightCol, result);
spiralOrderRight(matrix, topRow, leftCol, bottomRow, rightCol, result);
spiralOrderBottom(matrix, topRow, leftCol, bottomRow, rightCol, result);
spiralOrderLeft(matrix, topRow, leftCol, bottomRow, rightCol, result);
}
}
private static void spiralOrderRow(int[][] matrix, int row, int leftCol,
int rightCol, List result) {
for (int col = leftCol; col <= rightCol; col++) {
result.add(matrix[row][col]);
}
}
private static void spiralOrderCol(int[][] matrix, int col, int topRow,
int bottomRow, List result) {
for (int row = topRow; row <= bottomRow; row++) {
result.add(matrix[row][col]);
}
}
private static void spiralOrderTop(int[][] matrix, int topRow, int leftCol,
int bottomRow, int rightCol, List result) {
for (int col = leftCol; col < rightCol; col++) {
result.add(matrix[topRow][col]);
}
}
private static void spiralOrderRight(int[][] matrix, int topRow, int leftCol,
int bottomRow, int rightCol, List result) {
for (int row = topRow; row < bottomRow; row++) {
result.add(matrix[row][rightCol]);
}
}
private static void spiralOrderBottom(int[][] matrix, int topRow,
int leftCol, int bottomRow, int rightCol, List result) {
for (int col = rightCol; col > leftCol; col--) {
result.add(matrix[bottomRow][col]);
}
}
private static void spiralOrderLeft(int[][] matrix, int topRow, int leftCol,
int bottomRow, int rightCol, List result) {
for (int row = bottomRow; row > topRow; row--) {
result.add(matrix[row][leftCol]);
}
}
}