矩阵折叠

矩阵,如果行列数是偶数,折叠。

public class FoldMatrix {
	
 
	
	public static void main(String[] args) {
		int [][] mat = {{1,2,3,4,5,6,7,8,9},
						{1,2,3,4,5,6,7,8,9},
						{1,2,3,4,5,6,7,8,9},
						{1,2,3,4,5,6,7,8,9},
						{1,2,3,4,5,6,7,8,9},
						{1,2,3,4,5,6,7,8,9},
						{1,2,3,4,5,6,7,8,9},
						{1,2,3,4,5,6,7,8,9}};
		FoldMatrix fm = new FoldMatrix();
		int [][] pmat = fm.foldrm(mat);
		pmat = fm.foldlm(pmat);
		fm.printMat(pmat);
	}
	
	
	private int [][] foldrm(int[][] mat){
		int rc = mat.length;
		int lc = mat[0].length;
		int nrc = 0;
		int[][] rmat = null;
		
		//fold row
		if(rc%2==0){
			nrc = rc/2;
			 rmat = new int[nrc][lc];
			for(int i=0;i<nrc;i++){
				for(int j=0;j<lc;j++){
					rmat[i][j] = mat[i][j]+mat[rc-i-1][j];
				}
			}
		}
		if(rmat!=null&&(rmat.length%2==0)){
			rmat = foldrm(rmat);
		}
		return rmat==null?mat:rmat;
	}
	
	private int[][] foldlm(int[][] mat){
		 
		int lc = mat[0].length;
		int nlc = 0;
		int[][] lmat = null;
		//fold lie
		if(lc%2==0){
			 nlc = lc/2;
			lmat = new int[mat.length][nlc];
			for(int i=0;i<mat.length;i++){
				for(int j=0;j<nlc;j++){
					lmat[i][j] = mat[i][j]+ mat[i][lc-j-1];
				}
			}
		}
		
		if(lmat!=null&&(lmat[0].length%2==0)){
			lmat = foldlm(lmat);
		}
		 return lmat==null?mat:lmat;
		 
	}
	
	private void printMat(int[][] pmat){
		for(int i=0;i<pmat.length;i++){
			for(int j=0;j<pmat[0].length;j++){
				System.out.print(pmat[i][j] +",");
			}
			System.out.println();
		}
	}

}

这样是先写行折叠,再列折叠,可不可以一次递归行列都折叠。

猜你喜欢

转载自blog.csdn.net/os2046/article/details/53333446