54. 螺旋矩阵
题目描述
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
解题思路
1、获取行row、列column数量
2、边界定义
left = 0,top = 0,right = column - 1,bottom = row -1
注意点:从右向左时要判断 left <= right
从下向上时要判断 top <= bottom
代码实现
public class SpiralMatrix {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
int row = matrix.length;
int column = matrix[0].length;
int top = 0;
int bottom = row -1;
int left = 0;
int right = column -1;
for (int num = 1; num <= row * column;) {
for(int i=left;i<=right;i++){
list.add(matrix[top][i]);
num++;
}
top++;
for (int i = top; i <= bottom; i++) {
list.add(matrix[i][right]);
num++;
}
right--;
// 处理只有一行或一列的情况,避免重复添加元素
if (top <= bottom) {
// 从右到左
for (int i = right; i >= left; i--) {
result.add(matrix[bottom][i]);
num++;
}
bottom--;
}
if (left <= right) {
// 从下到上
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
num++;
}
left++;
}
return list;
}
public static void main(String[] args) {
SpiralMatrix solution = new SpiralMatrix();
int[][] result = {{1,2,3,4}};
solution.spiralOrder(result).stream().forEach(System.out::println);
}
}
925

被折叠的 条评论
为什么被折叠?



