Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Solution:
We can simulate the spiral route using a while loop.
At the first edge, we add a complete row into result list;
In two middle edges, we add row/ column which starts from the second index into result list;
At the last edge, we add the column which starts from the second index and end on (last – 1) index into the result list.
One time after the while loop, we shrink each edge of the size.
class Solution {
public List < Integer > spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix.length == 0) {
return res;
}
int rStart = 0;
int rEnd = matrix.length - 1;
int cStart = 0;
int cEnd = matrix[0].length - 1;
while (rStart <= rEnd && cStart <= cEnd) {
for (int c = cStart; c <= cEnd; c++) {
res.add(matrix[rStart][c]);
}
for (int r = rStart + 1; r <= rEnd; r++) {
res.add(matrix[r][cEnd]);
}
if (rStart < rEnd && cStart < cEnd) {
for (int c = cEnd - 1; c >= cStart; c--) {
res.add(matrix[rEnd][c]);
}
for (int r = rEnd - 1; r > rStart; r--) {
res.add(matrix[r][cStart]);
}
}
rStart++;
cStart++;
rEnd--;
cEnd--;
}
return res;
}
}
Time Complexity: O(N), where N is the total number of elements in the input matrix.
Space Complexity: O(N)