My normal java solution,use enum;

• it's easy to understand.
we just judge the direction and to do some change.
if we touch the boundary,we should change the direction and the index of (i,j);

``````enum Direction {
RIGHT,
DOWN,
LEFT,
UP
}

public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
if (matrix == null || matrix.length==0) {
return list;
}
int l = 0;
int r = matrix[0].length - 1;
int t = 0;
int b = matrix.length - 1;
int i = 0;
int j = 0;
Direction to = Direction.RIGHT;
while (true) {
if (t > b || l > r) {
break;
}
switch (to) {
case RIGHT:
if (j <= r) {
j++;
} else {
to = Direction.DOWN;
i++;
j--;
t++;
}
break;
case DOWN:
if (i <= b) {
i++;
} else {
to = Direction.LEFT;
j--;
i--;
r--;
}
break;
case LEFT:
if (j >= l) {
j--;
} else {
to = Direction.UP;
i--;
j++;
b--;
}
break;
case UP:
if (i >= t) {
i--;
} else {
to = Direction.RIGHT;
j++;
i++;
l++;
}
break;
}
}
return list;
}
``````

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