class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
ans.add(matrix[0][0]);
int[][] move = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int maxX = matrix.length - 1;
int maxY = matrix[0].length - 1;
int minX = 0;
int minY = 0;
int x = 0;
int y = 0;
while (true) {
boolean flag = false;
for (int direction = 0; direction < 4; direction++) {
int nextX = x + move[direction][0];
int nextY = y + move[direction][1];
while (nextX >= minX && nextX <= maxX && nextY >= minY && nextY <= maxY) {
flag = true;
x = nextX;
y = nextY;
ans.add(matrix[x][y]);
nextX = x + move[direction][0];
nextY = y + move[direction][1];
}
switch (direction) {
case 0:
minX++;
break;
case 1:
maxY--;
break;
case 2:
maxX--;
break;
default:
minY++;
break;
}
}
if (flag == false) {
return ans;
}
}
}
}