求助制作方阵思路
当n=4时,输出如下形式方阵:1 2 6 7
3 5 8 13
4 9 12 14
10 11 15 16
我看不出规律,求助
程序代码:
public class Dr {
private int[][] num;
private void print(int n) {
num = new int[n][n];
int count = 1;
int row = 0, col = 0;
int endRow = n - 1, endCol = n - 1, endCount = n * n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i + 1; j++) {
num[row][col] = count;
count++;
if (i % 2 == 0) {
row--;
col++;
} else {
row++;
col--;
}
if (row < 0) {
row++;
col--;
} else if (col < 0) {
col++;
row--;
}
}
if (row == 0) {
col++;
} else if (col == 0) {
row++;
}
for (int j = 0; j < i + 1; j++) {
if (i == n - 1)
break;
num[endRow][endCol] = endCount;
endCount--;
if (i % 2 != 0) {
endRow--;
endCol++;
} else {
endRow++;
endCol--;
}
if (endCol > n - 1) {
endCol--;
endRow++;
} else if (endRow > n - 1) {
endCol++;
endRow--;
}
}
if (endRow == n - 1) {
endCol--;
} else if (endCol == n - 1) {
endRow--;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%4d", num[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
Dr d = new Dr();
d.print(4);
System.out.println();
d.print(7);
}
}
程序代码:public class aa{
private static int s[][];
public static void main(String as[]){
int n1=0,n2=0,nn=0,o=4;
s=new int[o][o];
for(int u=0;u<o;u++){
for(int i=0,j=u;i<=u;i++,j--){
if(u%2==0){n1=j;n2=i;}else{n1=i;n2=j;}
nn++;
s[n1][n2]=nn;
if(u!=o-1){s[o-1-n1][o-1-n2]=o*o+1-nn;}
}
}
for(int i=0;i<o;i++){
String ss="";
for(int ii=0;ii<o;ii++){
ss+=s[i][ii]+" ";
}
System.out.println(ss);
}
}
}
