54. Spiral Matrix
Question
Given an m x n
matrix
, return all elements of the matrix
in spiral order.
Example:
Input: matrix = [[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]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
Algorithm
No trick question, implement step by step according to intuition.
Code
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
return res;
}
int bottom = matrix.length - 1;
int right = matrix[0].length - 1;
int left = 0;
int top = 0;
int row = left;
int col = top;
while (left <= right && top <= bottom) {
while (left <= right && top <= bottom && col <= right) {
res.add(matrix[row][col++]);
}
col = right;
top++;
row = top;
while (left <= right && top <= bottom && row <= bottom) {
res.add(matrix[row++][col]);
}
row = bottom;
right--;
col = right;
while (left <= right && top <= bottom && col >= left) {
res.add(matrix[row][col--]);
}
col = left;
bottom--;
row = bottom;
while (left <= right && top <= bottom && row >= top) {
res.add(matrix[row--][col]);
}
row = top;
left++;
col = left;
}
return res;
}
}