Spiral Matrix
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].
Solution
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
int b = matrix.length;
if (b == 0) {
return new ArrayList<>();
}
int a = matrix[0].length;
if (a == 0 && b == 0) {
return new ArrayList<>();
} else if (a == 1) {
for (int i = 0; i < b; i++) {
result.add(matrix[i][0]);
}
return result;
} else if (b == 1) {
for (int i = 0; i < a; i++) {
result.add(matrix[0][i]);
}
return result;
}
spiral(matrix, b, a, 0, result);
return result;
}
public void spiral(int[][] matrx, int b, int a, int k, List<Integer> result) {
if (k > a - k - 1 || k > b - k - 1) {
return;
}
if (k == a - k - 1 && k == b - k - 1) {
result.add(matrx[k][k]);
return;
}
for (int i = k; i < a - k - 1; i++) {
result.add(matrx[k][i]);
}
for (int i = k; i < b - k - 1; i++) {
result.add(matrx[i][a - k - 1]);
}
if (k == b - k - 1) {
result.add(matrx[b - k - 1][a - k - 1]);
} else {
for (int i = a - k - 1; i > k; i--) {
result.add(matrx[b - k - 1][i]);
}
}
if (k == a - k - 1) {
result.add(matrx[b - k - 1][k]);
} else {
for (int i = b - k - 1; i > k; i--) {
result.add(matrx[i][k]);
}
}
spiral(matrx, b, a, k + 1, result);
}
}