The idea is to read outer squares or rectangles and then move the sides to the middle.
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix.length == 0) {
return result;
}
int firstRow = 0;
int lastRow = matrix.length - 1;
int leftColumn = 0;
int rightColumn = matrix[0].length - 1;
while (firstRow <= lastRow && leftColumn <= rightColumn) {
// read first row
for (int i = leftColumn; i <= rightColumn; i++) {
result.add(matrix[firstRow][i]);
}
// read right column
for (int i = firstRow + 1; i <= lastRow; i++) {
result.add(matrix[i][rightColumn]);
}
// to avoid duplicates (reading it backwards)
if (firstRow < lastRow && leftColumn < rightColumn) {
// read last row
for (int i = rightColumn - 1; i >= leftColumn; i--) {
result.add(matrix[lastRow][i]);
}
// read left column
for (int i = lastRow - 1; i > firstRow; i--) {
result.add(matrix[i][leftColumn]);
}
}
firstRow++; // move first row down
rightColumn--; // move right column to left
lastRow--; // move last row up
leftColumn++; // move left column to right
}
return result;
}
}