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]
.
<pre name="code" class="java">public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (matrix == null|| matrix.length == 0 || matrix[0].length == 0) {
return res;
}
int m = matrix.length;
int n = matrix[0].length;
int total = Math.min(m, n) / 2;
for (int circle = 1; circle <= total; circle++) {
for (int i = circle - 1; i <= n - 1 - circle; i++) {
res.add(matrix[circle - 1][i]);
}
for (int i = circle - 1; i <= m - 1 - circle; i++) {
res.add(matrix[i][n - circle]);
}
for (int i = n - circle; i >= circle; i--) {
res.add(matrix[m - circle][i]);
}
for (int i = m - circle; i >= circle; i--) {
res.add(matrix[i][circle - 1]);
}
}
if (Math.min(m, n) % 2 != 0) {
if (m <= n) {
for (int i = total; i <= n - 1 - total; i++) {
res.add(matrix[total][i]);
}
} else {
for (int i = total; i <= m - 1 - total; i++) {
res.add(matrix[i][total]);
}
}
}
return res;
}
}