问题描述:从右上角到左下角沿反对角线打印方阵中的元素。假设矩阵为:java
1,2,3,4算法
5,6,7,8数组
9,10,11,12blog
13,14,15,16class
输出:4,3,8,2,7,12,1,6,11,16,5,10,15,9,14,13,import
分析:这个没有什么算法问题,就是纯粹的代码技巧问题,经过画图能够找出规律,只要肯定每条反对角线的两端的坐标,就能够打印出对角线上的元素。所以能够将其分红两部分打印,定义两个变量row和column来保存矩阵的行数和列数,定义两个变量x和y来做为临时坐标变量。可肯定出两部分的范围为打印(0,x)-(y,column-1)对角线上的元素,打印(x,0)-(row-1,y)对角线上的元素,具体代码以下:变量
import java.util.*; public class Main1 { public static void orderprint(int a[][]){ if(a==null){ System.out.println("数组不存在"); return ; } int row=a.length,column=a[0].length; if(row==0 || column==0){ System.out.println("数组为空数组"); return ; } int y=0,x=column-1; while(x>=0 && y<=row-1){ //打印(0,x)-(y,column-1)对角线上的元素 for(int j=x,i=0;j<=column-1 && i<=y;i++,j++) System.out.print(a[i][j]+","); x--;y++; } x=1;y=column-2; while(y>=0 && x<=row-1){ //打印(x,0)-(row-1,y)对角线上的元素 for(int i=x,j=0;i<=row-1 && j<=y;i++,j++) System.out.print(a[i][j]+","); x++;y--; } } public static void main(String[] args) { // TODO 自动生成的方法存根 int a[][]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; orderprint(a); } }
样例输出结果为:4,3,8,2,7,12,1,6,11,16,5,10,15,9,14,13,技巧