给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 输出:[1,2,3,4,8,12,11,10,9,5,6,7]
package TOP11_20;
import java.util.ArrayList;
import java.util.List;
//螺旋矩阵
/*给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
*/
public class Top19 {
// 转圈遍历
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix.length == 0) {
return result;
}
int length = matrix.length;
int height = matrix[0].length;
int totalNums = length * height;
int left = 0;
int right = height - 1;
int top = 0;
int bottom = length - 1;
while (totalNums > 0) {
for (int i = left; i <= right && totalNums > 0; i++) {
result.add(matrix[top][i]);
totalNums--;
}
top++;
for (int i = top; i <= bottom && totalNums > 0; i++) {
result.add(matrix[i][right]);
totalNums--;
}
right--;
for (int i = right; i >= left && totalNums > 0; i--) {
result.add(matrix[bottom][i]);
totalNums--;
}
bottom--;
for (int i = bottom; i >= top && totalNums > 0; i--) {
result.add(matrix[i][left]);
totalNums--;
}
left++;
}
return result;
}
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
System.out.println(spiralOrder(matrix));
}
}
harryptter / LeetcodeTop100 · GitCode