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].
我想着把这个二维数组分成一层一层的环,然后一层一层的遍历,就能得到,而遍历环就是上边右边下边左边。就是要控制好循环结束之类的。
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0)
return res;
int size = matrix.length * matrix[0].length;
int len = Math.min(matrix.length, matrix[0].length);
for (int i = 0; i < len; i++) {
if (res.size() == size)
break;
visitCircle(res, matrix, i);
}
return res;
}
public void visitCircle(List<Integer> list, int[][] a, int m) {
int len = a[0].length, hlen = a.length;
for (int i = m; i < len - m; i++) {
list.add(a[m][i]);
}
for (int i = 1 + m; i < hlen - m; i++) {
list.add(a[i][len - m - 1]);
}
if (hlen - 2 * m == 1 || len - 2 * m == 1)
return;
for (int i = len - 2 - m; i >= m; i--) {
list.add(a[hlen - m - 1][i]);
}
for (int i = hlen - m - 2; i > m; i--) {
list.add(a[i][m]);
}
}
还有一种方法,跟我这个其实是一个意思,但是他没有这样表达。
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> rst = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0)
return rst;
int rows = matrix.length;
int cols = matrix[0].length;
int count = 0;
while (count * 2 < rows && count * 2 < cols) {
for (int i = count; i < cols - count; i++)
rst.add(matrix[count][i]);
for (int i = count + 1; i < rows - count; i++)
rst.add(matrix[i][cols - count - 1]);
if (rows - 2 * count == 1 || cols - 2 * count == 1)
// if only one row /col remains
break;
for (int i = cols - count - 2; i >= count; i--)
rst.add(matrix[rows - count - 1][i]);
for (int i = rows - count - 2; i >= count + 1; i--)
rst.add(matrix[i][count]);
count++;
}
return rst;
}