# Let that gluttonous snake swallow those numbers in spiral way!!!

• ``````public class Solution {
private static enum Direction {
EAST, WEST, SOUTH, NORTH
}

public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> swallowNumbers = new ArrayList<>();    // record the numbers swallowed by the gluttonous snake

if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return swallowNumbers;
}

int rows = matrix.length;
int cols = matrix[0].length;
int totalCount = rows * cols;

boolean[][] visited = new boolean[rows][cols];    // to record which slot have been visited by the gluttonous snake
Direction currentDirection = Direction.EAST;
int currentRow = 0;
int currentCol = 0;

int swallowCount = 1;
visited[currentRow][currentCol] = true;

while (swallowCount < totalCount) {
switch (currentDirection) {
case EAST:
if (currentCol + 1 >= cols || visited[currentRow][currentCol + 1]) {
// turn to the next direction: SOUTH
currentDirection = Direction.SOUTH;
} else {
// go one step towards the east and swallow that number
currentCol++;
visited[currentRow][currentCol] = true;
swallowCount++;
}
break;

case SOUTH:
if (currentRow + 1 >= rows || visited[currentRow + 1][currentCol]) {
// turn to the next direction: WEST
currentDirection = Direction.WEST;
} else {
// go one step towards the south and swallow that number
currentRow++;
visited[currentRow][currentCol] = true;
swallowCount++;
}
break;

case WEST:
if (currentCol - 1 < 0 || visited[currentRow][currentCol - 1]) {
// turn to the next direction: NORTH
currentDirection = Direction.NORTH;
} else {
// go one step towards the west and swallow that number
currentCol--;
visited[currentRow][currentCol] = true;
swallowCount++;
}
break;

case NORTH:
if (currentRow - 1 < 0 || visited[currentRow - 1][currentCol]) {
// turn to the next direction: EAST
currentDirection = Direction.EAST;
} else {
// go one step towards the west and swallow that number
currentRow--;
visited[currentRow][currentCol] = true;
swallowCount++;
}
break;
}
}

return swallowNumbers;
}
}
``````

You can see that my algorithm is very interesting, like a game, isn't it? When you start to study my algorithm, it is like playing gluttonous snake game!!!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.