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 List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<Integer>();
if (matrix.length == 0) {
return result;
}
int rowBegin = 0;
int rowEnd = matrix.length - 1;
int colBegin = 0;
int colEnd = matrix[0].length - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
for (int j = colBegin; j <= colEnd; j++) {
result.add(matrix[rowBegin][j]);
}
rowBegin++;
for (int j = rowBegin; j <= rowEnd; j++) {
result.add(matrix[j][colEnd]);
}
colEnd--;
if (rowBegin <= rowEnd) {
for (int j = colEnd; j >= colBegin; j--) {
result.add(matrix[rowEnd][j]);
}
}
rowEnd--;
if (colBegin <= colEnd) {
for (int j = rowEnd; j >= rowBegin; j--) {
result.add(matrix[j][colBegin]);
}
}
colBegin++;
}
return result;
}