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]
.
思路:这个算法是我见到的比较好理解的。关键点就是:每进行下一次收集的时候,要判断边界是否超出。
if(++beginX>endX) break;
事实上,beginX已经加1了,这样接下来的收集,直接从beginX开始。
其他依次类推。这个算法,好理解,无需考虑其他极端情况。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
int m = matrix.length;
int n = matrix[0].length;
int startX = 0; int endX = m - 1;
int startY = 0; int endY = n - 1;
while(true) {
// top;
for(int j = startY; j <= endY; j++) {
list.add(matrix[startX][j]);
}
if(++startX > endX) break;
// right;
for(int i = startX; i <= endX; i++) {
list.add(matrix[i][endY]);
}
if(--endY < startY) break;
// bottom;
for(int j = endY; j >= startY; j--) {
list.add(matrix[endX][j]);
}
if(--endX < startX) break;
// left;
for(int i = endX; i >= startX; i--) {
list.add(matrix[i][startY]);
}
if(++startY > endY) break;
}
return list;
}
}