Java for LeetCode 054 Spiral Matrix

时间:2023-12-29 13:12:08

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].

解题思路:

螺旋阵列,使用up down left right 四个指针标记上下左右的位置即可,JAVA实现如下:

static public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<Integer>();
if (matrix.length == 0 || matrix[0].length == 0)
return list;
int left = 0, right = matrix[0].length - 1, up = 0, down = matrix.length - 1;
while (left <= right && up <= down) {
for (int i = left; i <= right&&up<=down; i++)
list.add(matrix[up][i]);
up++;
for (int i = up; i <= down&&left<=right; i++)
list.add(matrix[i][right]);
right--;
for (int i = right; i >= left&&up<=down; i--)
list.add(matrix[down][i]);
down--;
for (int i = down; i >= up&&left<=right; i--)
list.add(matrix[i][left]);
left++;
}
return list;
}