public class Solution {
/**
* @param matrix a matrix of m x n elements
* @return an integer list
*/
public List<Integer> spiralOrder(int[][] matrix) {
// Write your code here
List<Integer> result = new ArrayList<>();
if (matrix == null) return result;
int row = matrix.length;
if (row == 0) return result;
int column = matrix[0].length;
tranverseEdge(result, 0, 0, row, column, matrix);
return result;
}
private void tranverseEdge(List<Integer> result, int startRow, int startColumn, int rowLength, int columnLength, int[][] matrix) {
if (columnLength == 0 || rowLength == 0) return; //这里是 || 不能是 && 比如 2 * 4的
if (rowLength == 1) { //当省一行或者一列要停,否则会重复遍历这一行或者一列。
for (int i = startColumn; i < startColumn + columnLength; i++) {
result.add(matrix[startRow][i]);
}
return;
}
if (columnLength == 1) {
for (int i = startRow; i < startRow + rowLength; i++) {
result.add(matrix[i][startColumn]);
}
return;
}
for (int i = startColumn; i < startColumn + columnLength - 1; i++) {
result.add(matrix[startRow][i]);
}
for (int i = startRow; i < startRow + rowLength - 1; i++) {
result.add(matrix[i][startColumn + columnLength - 1]);
}
for (int i = startColumn + columnLength - 1; i> startColumn;i--) {
result.add(matrix[startRow + rowLength - 1][i]);
}
for (int i = startRow + rowLength - 1; i > startRow; i--) {
result.add(matrix[i][startColumn]);
}
tranverseEdge(result, startRow + 1, startColumn + 1, rowLength - 2, columnLength - 2,matrix);
}
}
网友评论