16.1 Spiral Order Matrix I (Medium)
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, 6 ],
[ 7, 8, 9 ]
]
You should return
[1,2,3,6,9,8,7,4,5].
https://leetcode.com/problems/spiral-matrix/
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(matrix==null||matrix.length==0||matrix[0].length==0) return result;
int top=0;
int left=0;
int bottom=matrix.length-1;
int right=matrix[0].length-1;
int direction =0;
while(top<=bottom && left<=right){
if(direction==0){ //move right
for(int i=left;i<=right;i++){
result.add(matrix[top][i]);
}
top++;
direction=1;
}
else if(direction==1){ //move down
for(int i=top;i<=bottom;i++){
result.add(matrix[i][right]);
}
right--;
direction=2;
}
else if(direction==2){ //move left
for(int i=right;i>=left;i--){
result.add(matrix[bottom][i]);
}
bottom--;
direction=3;
}
else if(direction==3){ //move up
for(int i=bottom;i>=top;i--){
result.add(matrix[i][left]);
}
left++;
direction=0;
}
}
return result;
}
}