java算法----斜角矩阵的实现

package com.zhenlvwang.interview;

/**
 * 实现N*N的矩阵,使得其数据为
 * 1 3 6
 * 2 5
 * 4
 * @author yangjianzhou
 *
 */
public class Problem3 {

	public static void main(String[] args) {
		Problem3 p = new Problem3();
		int [][] xx =p.createMatrix(10);
		for(int i=0;i<xx.length;i++){
			for(int j=0;j<xx[i].length;j++){
				System.out.print(xx[i][j]+"  ");
			}
			System.out.println();
		}
	}
	
	public int[][] createMatrix(int N){
		
		int[][] xx = new int[N][N];
		for(int i=0;i<N;i++){
			for(int j=0;j<N;j++){
				if(i==0&&j==0){
					xx[i][j]=1;
				}else if(j==0){
					xx[i][j] = xx[i-1][j]+i; 
				}else if(i+j<N){
					xx[i][j] = xx[i][j-1]+j+1+i;
				}else{
					xx[i][j] = 0;
				}
			}
		}
		for(int i=N-1;i>=0;i--){
			for(int j=N-1;j>=0;j--){
				if(i==N-1&&j==N-1){
					xx[i][j] = N*N;
				}else if(j==N-1){
					xx[i][j] = xx[i+1][j]-(N-i-1);
				}else if(i+j>=N){
					xx[i][j] = xx[i][j+1]-2*N+i+j+1;
				}
			}
		}
		return xx;
	}
}



1  3  6  10  15  21  28  36  45  55  
2  5  9  14  20  27  35  44  54  64  
4  8  13  19  26  34  43  53  63  72  
7  12  18  25  33  42  52  62  71  79  
11  17  24  32  41  51  61  70  78  85  
16  23  31  40  50  60  69  77  84  90  
22  30  39  49  59  68  76  83  89  94  
29  38  48  58  67  75  82  88  93  97  
37  47  57  66  74  81  87  92  96  99  
46  56  65  73  80  86  91  95  98  100  

你可能感兴趣的:(java算法)