yahoo笔试题。
输出下三角矩阵螺旋数,比如,输入为4,则输出:
1
2 9
3 10 8
4 5 6 7
输入为5,则输出:
1
2 12
3 13 11
4 14 15 10
5 6 7 8 9
代码如下,大致思想就是设一个方向变量,-1为向下,0为向右,1为向左上,然后控制二维数组下标为数组赋值,最后打印。
修改print()方法的传入参数即可。
public class Sort {
public static void main(String[] args){
print(5);
}
static void print(int n){
int l = n;
int sum = 0;
for(int i=1; i<=n; i++){
sum += i;
}
int a[][] = new int[n][n];
int s = 1;
int i = 0, j = 0;
int d = -1;
for(int k=1; k<=sum; k++){
switch (d) {
case -1:
a[i][j] = s++;
if(i<n-1){
i++;
}
else{
n--;
j++;
d = 0;
}
break;
case 0:
a[i][j] = s++;
if(i == (l-1)){
if(j<i){
j++;
}
else{
i--;
j--;
d = 1;
}
}
else if(a[i][j+1] == 0){
j++;
}
else{
i--;
j--;
d = 1;
}
break;
case 1:
a[i][j] = s++;
if(a[i-1][j-1] == 0){
i--;
j--;
}
else{
i++;
d = -1;
}
break;
default:
break;
}
}
for(int p=0; p<l; p++){
for(int q=0; q<=p; q++){
System.out.print(a[p][q] + " ");
}
System.out.println();
}
}
}