思想:
每一轮按照如下顺序去打印:
step1:先打印最上面那一行
step2:再打印最右边那一列
step3:再打印最下边那一列(注意这是必须按从右往左的顺序打印)
step4:再打印最左边那一列(注意必须按由下往上的顺序打印)
【tips:】注意不要打印重复值
一轮打印结束,将行的区间以及列的区间均内收1位(也就是将整个矩阵内缩一位)),再去打印,直到下标违法时(起始坐标>终止坐标)为止
class Solution {
public int[] spiralOrder(int[][] matrix) {
int rows = matrix.length;
int cols = (rows!=0)?matrix[0].length:0;
int itemMount = rows*cols;
int[] res = new int[itemMount];
// row:当前矩阵行的起始值 rows:当前矩阵行的终止值(最大值)col与cols同理
int row = 0,col = 0;
rows--;
cols--;
int idx = 0;
while(row<=rows&&col<=cols){
//先打印最上面那一行
for(int i=col;i<=cols;i++){
res[idx++] = matrix[row][i];
//注意这里,当存了足够的元素后就返回,要不然会加入重复元素
if(idx==itemMount){
return res;
}
}
//再打印最右边那一列
for(int j=row+1;j<=rows;j++){
res[idx++] = matrix[j][cols];
if(idx==itemMount){
return res;
}
}
//再打印最下边那一列(注意这是必须按从右往左的顺序打印)
for(int k=cols-1;k>=col;k--){
res[idx++] = matrix[rows][k];
if(idx==itemMount){
return res;
}
}
//再打印最左边那一列(注意必须按由下往上的顺序打印)
for(int l=rows-1;l>=row+1;l--){
res[idx++] = matrix[l][col];
if(idx==itemMount){
return res;
}
}
//一轮打印完成,将整个矩阵内缩一位
col++;
row++;
cols--;
rows--;
}
return res;
}
}
另一种题型:反向生成一个螺旋数组:
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。腾讯精选T59
思想:最后应该生成1个n*n的矩阵
借助螺旋矩阵-|的遍历思想
每一轮按照如下顺序去打印:
step1:先打印最上面那一行
step2:再打印最右边那一列
step3:再打印最下边那一列(注意这是必须按从右往左的顺序打印)
step4:再打印最左边那一列(注意必须按由下往上的顺序打印)
【tips:】注意不要打印重复值
一轮打印结束,将行的区间以及列的区间均内收1位(也就是将整个矩阵内缩一位)),再去打印,直到下标违法时(起始坐标>终止坐标)为止
class Solution {
public int[][] generateMatrix(int n) {
int item = 1;
int rows = n-1,cols = n-1;
int col = 0,row = 0;
int total = n*n;
int[][] res = new int[n][n];
while(row<=rows&&col<=cols){
//step1
for(int j=col;j<=cols;j++){
res[row][j] = item;
if(item==total){
return res;
}
item++;
}
//step2
for(int i=row+1;i<=rows;i++){
res[i][cols] = item;
if(item==total){
return res;
}
item++;
}
//step3
for(int j=cols-1;j>=col;j--){
res[rows][j] = item;
if(item==total){
return res;
}
item++;
}
//step4
for(int i=rows-1;i>row;i--){
res[i][col] = item;
if(item==total){
return res;
}
item++;
}
row++;
col++;
rows--;
cols--;
}
return res;
}
}