题目描述
给定一个整数n,将数字1到n^2n2按螺旋的顺序填入n×n的矩阵
例如:
给出的n=3,
你应该返回如下矩阵:
public int[][] generateMatrix (int n) {
int[][] result = new int[n][n];
if(n<1){
return result;
}
int count=1;//依次累加,存放到矩阵中
int rowStart = 0,rowEnd = n-1;//当前圈的行头、行尾下标
int colStart = 0,colEnd = n-1;//当前圈的列头、列尾
while(count<=n*n){ //依次为每个外圈赋值
for(int i=colStart;i<=colEnd;i++){ //为当前圈的第一行赋值
result[rowStart][i] = count++;
}
for(int i=rowStart+1;i<=rowEnd;i++){//为当前圈的最后一列赋值
result[i][colEnd] = count++;
}
for(int i=colEnd-1;i>=colStart;i--){为当前圈的最后一行赋值
result[rowEnd][i] = count++;
}
for(int i=rowEnd-1;i>rowStart;i--){//为当前圈的第一列赋值
result[i][colStart] = count++;
}
rowStart++; //更新为下一圈的头、尾下标
rowEnd--;
colStart++;
colEnd--;
}//while
return result;
}