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]
.
第二次写,这样子表示更好理解一些,注意最后两层for 循环 判断条件是大于
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null) {
return null;
}
List<Integer> list = new ArrayList<Integer>();
if (matrix.length == 0 || matrix[0].length == 0) {
return list;
}
int top = 0;
int left = 0;
int bottom = matrix.length - 1;
int right = matrix[0].length - 1;
while(top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
list.add(matrix[top][i]);
}
for (int i = top + 1; i <= bottom; i++) {
list.add(matrix[i][right]);
}
if (bottom == top || left == right) {
break;
}
//if (bottom != top) {
for (int i = right - 1; i >= left; i--) {
list.add(matrix[bottom][i]);
}
//}
//if (left != right) {
for (int i = bottom - 1; i > top; i--) {
list.add(matrix[i][left]);
}
//}
top++;
bottom--;
left++;
right--;
}
return list;
}
}