public List<Integer> spiralOrder(int[][] matrix){ List<Integer> results = new ArrayList<>();
if (matrix.length == 0) { return results; }
// current index of the position int indexX = 0; int indexY = 0;
// up, right, down, left int[][] direction = newint[][]{ {0, -1}, {1, 0}, {0, 1}, {-1, 0} };
// moving direction, start towards right Towards towards = Towards.RIGHT;
// mark the position of boundary int topBorder = -1; int bottomBorder = matrix.length; int leftBorder = -1; int rightBorder = matrix[0].length;
while (true) { // finished if (results.size() == matrix.length * matrix[0].length) { return results; }
results.add(matrix[indexY][indexX]);
switch (towards) { // move right case RIGHT: // reach the boundary if (indexX + 1 == rightBorder) { // change direction towards = Towards.DOWN; // move the boundary topBorder++;