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].
可以为矩阵设置上下左右四个边界,每次绕着这四个边界打印元素。实现代码如下:
1 public class Solution {
2 public ArrayList<Integer> spiralOrder(int[][] matrix) {
3 ArrayList<Integer> ret = new ArrayList<Integer>();
4 if (matrix.length == 0) return ret;
5 int upper = 0, bottom = matrix.length - 1;
6 int left = 0, right = matrix[0].length - 1;
7 int i = 0, j = 0;
8 while (true) {
9 for (i = left; i <= right; i++) {
10 ret.add(matrix[upper][i]);
11 }
12 if (++upper > bottom) break;
13 for (j = upper; j <= bottom; j++) {
14 ret.add(matrix[j][right]);
15 }
16 if (--right < left) break;
17 for (i = right; i >= left; i--) {
18 ret.add(matrix[bottom][i]);
19 }
20 if (--bottom < upper) break;
21 for (j = bottom; j >= upper; j--) {
22 ret.add(matrix[j][left]);
23 }
24 if (++left > right) break;
25 }
26 return ret;
27 }
28 }