最近接触到了一个有意思的题目,花了点时间解答了一下,在此分享下!
题目为:
package macor.matrix;
import java.util.*;
public class NMMatrix {
int n;
int m;
public NMMatrix(int n, int m){
this.n = n;
this.m = m;
}
public void generateArray(int n,int m){
int i = 0; //行
int j = 0; //列
int k = 1; //运动方向. k =1 表示运动方向为从左往右移动;k=2 表示从右上角往左下角移动; k=3 表示向下移动 ;k=4 表示从左下角网右上角移动
int [][] data =new int [n][m];
data[0][0] = 1;
while( i!=n-1 || j !=m-1){
// System.out.println("i="+i+" j="+j+" d="+data[i][j]+ " k="+k);
if(k == 1){
data[i][j+1] = data[i][j] + 1;
j = j + 1;
if(i == n-1){
k = 4;
}else{
k = 2;
}
}else if(k == 2){
data[i+1][j-1] = data[i][j] + 1;
j = j - 1;
i = i +1;
if( j == 0 && i != n-1){
k = 3;
}else if( i == n-1){
k = 1;
}else{
k = 2;
}
}else if(k == 3){
data[i+1][j] = data[i][j] + 1;
i = i+1;
if( j == m-1){
k = 2;
}else {
k = 4;
}
}else if(k == 4){
data[i-1][j+1] = data[i][j] + 1;
j = j + 1;
i = i - 1;
if(i == 0 && j != m-1){
k = 1;
}else if( j == m-1 )
{
k = 3;
}else{
k = 4;
}
}
}
//System.out.println("Finished");
//System.out.println("i="+i+" j="+j+" d="+data[i][j]+ " k="+k);
System.out.println("生成的矩阵如下:");
//显示矩阵
for(int a=0;a