leetcode 54 spiral matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

1
2
3
4
5
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

class {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0) return ans;
int upperRow = 0;
int bottomRow = matrix.length-1;
int leftColumn = 0;
int rightColumn = matrix[0].length-1;

while(upperRow <= bottomRow && leftColumn <= rightColumn){
for(int i=leftColumn; i<=rightColumn; i++){
ans.add(matrix[upperRow][i]);
}
upperRow ++;

for(int i=upperRow; i<= bottomRow; i++){
ans.add(matrix[i][rightColumn]);

}
rightColumn --;

if(upperRow <= bottomRow){
for(int i=rightColumn; i>= leftColumn; i--){
ans.add(matrix[bottomRow][i]);
}
bottomRow --;
}

if(leftColumn <= rightColumn){
for(int i=bottomRow; i>= upperRow; i--){
ans.add(matrix[i][leftColumn]);
}
leftColumn ++;
}

}
return ans;
}
}
  • Using four pointers to point the four outside boundaries.