題目描述
給你一個 m 行 n 列的矩陣 matrix ,請按照 順時針螺旋順序 ,返回矩陣中的所有元素。
示例
輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
輸出:[1,2,3,6,9,8,7,4,5]
代碼
private static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length <= 0) {
return result;
}
int top = 0;
int right = matrix[0].length - 1; //
int left = 0;
int bottom = matrix.length - 1; // 二維數(shù)組的lengh是行數(shù)
int remainElementCount = matrix.length * matrix[0].length; // 二維數(shù)組中元素數(shù)量
while (remainElementCount > 0) {
// 從左上到右上
for (int i = left; i <= right && remainElementCount > 0; i++ ) {
result.add(matrix[top][i]);
remainElementCount --;
}
top ++;
// 從右上往右下
for (int j = top; j <= bottom && remainElementCount > 0; j++ ) {
result.add(matrix[j][right]);
remainElementCount --;
}
right --;
// 從右下到左下
for (int k = right; k >= left && remainElementCount > 0; k -- ) {
result.add(matrix[bottom][k]);
remainElementCount --;
}
bottom --;
// 從左下到左上
for (int e = bottom; e >= top && remainElementCount > 0; e -- ) {
result.add(matrix[e][left]);
remainElementCount --;
}
left ++;
}
return result;
}