Given an m x n matrix, return all elements of the matrix in spiral order.
# 1. 横向遍历m,纵向遍历n-1;
# 2. 横向遍历m-1,纵向遍历n-2;
# 3. 横向遍历m-2,纵向遍历n-3;.......
# 4. 直到有一方向遍历长度为0时终止。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList();
int n = matrix.length;
int m = matrix[0].length;
int i = 0, j = -1;
int flag = 1;
while(m > 0 && n > 0){
for(int x = 0;x < m; x++){
j += flag;
res.add(matrix[i][j]);
}
for(int x = 0;x < n - 1; x++){
i += flag;
res.add(matrix[i][j]);
}
flag *= -1;
m -= 1;
n -= 1;
}
return res;
}
}