# My Java solution. Easy to understand with explanation.

• We can define xStart, yStart, xLimit, yLimit. After each iteration we do

``````xStart++;
yStart++;
xLimit--;
yLimit--;
``````

The time complexity is O(mn) since we need to fill all the m*n positions in the resulting arraylist;

``````    public List<Integer> spiralOrder(int[][] matrix) {
int length = matrix.length;
if (length == 0) {
return new ArrayList<Integer>();
}
int width = matrix[0].length;
if (width == 0) {
return new ArrayList<Integer>();
}
int total = length * width;
List<Integer> result = new ArrayList<>();
int start = 0;
int xStart = 0;
int yStart = 0;
int xLimit = width - 1;
int yLimit = length - 1;
int i = xStart;
int j = yStart;
while (start < total) {
while (start < total && i <= xLimit) {
start++;
}
i--;
j++;
while (start < total && j <= yLimit) {
start++;
}
j--;
i--;
while (start < total && i >= xStart) {
start++;
}
i++;
j--;
while (start < total && j > yStart) {
start++;
}
xStart++;
yStart++;
xLimit--;
yLimit--;
i = xStart;
j = yStart;
}
return result;
}
``````

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