# EASY JAVA SOLUTION with explaination

• Just go via the first row, last col, last row first col.
Then, second row, second last col, second last row and second col.
And keeping doing this until the list size is equal the total element number of matrix.

public class Solution {

``````public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> re = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0) return re;
int m = matrix.length;
int n = matrix[0].length;
int start = 0;
int upRow = 0, boRow = m-1, leCol = 0, riCol = n-1;
while(true){
for(int i = start; i <= riCol; i++){
re.add(matrix[upRow][i]);
}
if(re.size() == m*n) return re;
start++;
for(int i = start; i <= boRow; i++){
re.add(matrix[i][riCol]);
}
if(re.size() == m*n) return re;
for(int i = n - 1 - start; i >= leCol; i--){
re.add(matrix[boRow][i]);
}
if(re.size() == m*n) return re;
for(int i = m - 1 - start; i > upRow; i--){
re.add(matrix[i][leCol]);
}
if(re.size() == m*n) return re;
riCol--; boRow--; leCol++; upRow++;
}
}
``````

}

• Thanks. This is easy to understand.

• This post is deleted!

• @tracy_zh Thank you for replying!

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