螺旋数组2(Java)
题目(Leetcode中59题)
给定一个正整数,生成一个包含1到n的平方的所有元素,且元素按顺时针顺序排列的n×n正方形矩阵
方法1:思路分析如下:顺时针顺序排列的时候,先行后列,行不变列增,列不变行增,列不变行减,行不变列减。一个循环执行一次操作。所以我们先计算下循环了几次,情况分为两种,当n为奇数和偶数的时候,为奇数的时候中心会多出一个单独的数,value==n*n;偶数时候则不用考虑。
package spiralmatrix;
public class SpiralMtwo {
public static void main(String []args){
SpiralMtwo s = new SpiralMtwo();
int n = 3;
int b[][] = s.generateMatrix(3);
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
System.out.println(b[i][j]);
}
}
}
public int[][] generateMatrix(int n){
// compute the cycle times 如何确定每个循环的上下界十分重要,在这里上下界是变化的,
int loop = n/2;
int mid = n/2;
int offset=1; //每循环一次位移量会减少2
int startx=0,starty=0;
int [][]a = new int [n][n];
int count=1; //计数器
while(loop-- > 0){
int j=starty;
int i=startx;
for(j=starty; j<startx+n-offset; j++){//行不变列增
a[startx][j] = count++;
}
for(i=startx; i<starty+n-offset; i++){//列不变行增
a[i][j] = count++;
}
for(; j>starty; j--){//列不变行减
a[i][j] = count++;
}
for(; i>startx; i--){//行不变列减
a[i][j] = count++;
}
startx++;
starty++;
offset = offset+2;
}
if(n%2==1){ //考虑当n为奇数的情况
a[mid][mid] = n*n;
}
return a;
}
}
方法2:上面说到了一个循环中四种不同的变化,迷宫问题中有设置位置导向变量,在这里我们依然可以定义两个导向数组dx,dy。int [ ]dx = {0,1,0,-1}; int [ ]dy = {1,0,-1,0};
public int[][] generateMatrix(int n){
// compute the cycle times 如何确定每个循环的上下界十分重要,在这里上下界是变化的,
int a[][]=new int[n][n];
int []dx = {0,1,0,-1};
int []dy = {1,0,-1,0};
for(int i=0, startx=0,starty=0,d=0; i<n*n; i++){
a[startx][starty] = i+1;
int curx = dx[d] + startx, cury = dy[d] + starty;
if(curx<0 || cury<0 || curx>=n || cury>=n || a[curx][cury]!=0){
d = (d+1)%4;
}
startx = dx[d]+startx;
starty = dy[d]+starty;
}
return a;
}
方法三:结合两种技巧;待续。。。