1、生成或者遍历正方形螺旋矩阵
2、生成或者遍历非正方形螺旋矩阵
1、力扣59题:给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
按照右填充,下填充,左填充,下填充的顺序不断循环填充。
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
int number = 1;
// left right top bottom 指向的是当前二维数组ans带填充的范围 包括其指针本身
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
while(left <= right && top <= bottom){
//向右边填充
for(int i = left;i <= right;i++){
ans[top][i] = number;
number++;
}
top++;
//向下填充
for(int j = top;j <= bottom;j++){
ans[j][right] = number;
number++;
}
right--;
//向左填充
for(int k = right;k >= left;k--){
ans[bottom][k] = number;
number++;
}
bottom--;
//向上填充
for(int m = bottom;m >= top;m--){
ans[m][left] = number;
number++;
}
left++;
}
return ans;
}
2、力扣54题:给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
这时矩阵不再一定是正方形矩阵了,需要在上面的代码上添加判断条件!
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
int left = 0;
int right = matrix[0].length;
int top = 0;
int bottom = matrix.length;
while(top < bottom && left < right){
for(int i = left;i < right;i++){
list.add(matrix[top][i]);
}
top++;
// 一定要加,例如1✖2 已经填充完成 若不加在下面的添加会添加多余的元素
if(top >= bottom){
break;
}
for(int j = top;j < bottom;j++){
list.add(matrix[j][right - 1]);
}
right--;
// 一定要加,例如2✖1 到这里已经填充完成
if(left >= right){
break;
}
for(int k = right - 1;k >= left;k--){
list.add(matrix[bottom - 1][k]);
}
bottom--;
if(top >= bottom){
break;
}
for(int m = bottom - 1;m >= top;m--){
list.add(matrix[m][left]);
}
left++;
// 不需要添加了,因为在下次循环前将判断循环条件
}
return list;
}