Leetcode 54. Spiral Matrix (Medium) (java)
Tag: Array
Difficulty: Medium
/*
54. Spiral Matrix (Medium)
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 class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null || matrix.length == 0) {
return res;
}
int m = matrix.length - 1, n = matrix[0].length - 1, h = 0, l = 0;
while (true) {
for (int col = l; col <= n; col++) {
res.add(matrix[h][col]);
}
if (++h > m) {
break;
}
for (int row = h; row <= m; row++) {
res.add(matrix[row][n]);
}
if (l > --n) {
break;
}
for (int col = n; col >= l; col--) {
res.add(matrix[m][col]);
}
if (--m < h) {
break;
}
for (int row = m; row >= h; row--) {
res.add(matrix[row][l]);
}
if (++l > n) {
break;
}
}
return res;
}
}